Re: Using count() as an array index [message #178425 is a reply to message #178422] |
Sat, 16 June 2012 21:43 |
Scott Johnson
Messages: 196 Registered: January 2012
Karma:
|
Senior Member |
|
|
On 6/16/2012 11:44 AM, Jerry Stuckle wrote:
> On 6/16/2012 1:56 PM, Martin Leese wrote:
>> Chuck Anderson wrote:
>>
>>> You can not use a function call within a quoted string.
>>>
>>> You should use:
>>>
>>> echo $anArray[count($array)] . "\n";
>>
>> Thank you. I actually understood this
>> explanation.
>>
>
> Actually, you can easily use a function call within a quoted string, but
> since it is not a simple variable, you need to use curly braces, i.e.
>
> <?php
> $anArray[1] = "This is element one";
> $anArray[2] = "This is element two";
> $anArray[3] = "This is the last element";
> echo "{$anArray[count($anArray)]}\n";
> ?>
>
> prints "This is the last element" (without the quotes, of course).
>
> Be aware, though - the typical array in PHP starts counting at 0, not 1.
> So an array of 3 elements would be numbered 0, 1 and 2. In this case, an
> element with an index of 3 (count($anArray)) is not set (and will give a
> warning if you try to use it).
>
> You need to get used to this idea; it's used throughout PHP.
>
Oh how I have come to love those curly braces.. :)
|
|
|