Re: Using count() as an array index [message #178416 is a reply to message #178410] |
Fri, 15 June 2012 21:44 ![Go to previous message Go to previous message](/forum/theme/default/images/up.png) ![Go to next message Go to previous message](/forum/theme/default/images/down.png) |
Chuck Anderson
Messages: 63 Registered: September 2010
Karma:
|
Member |
|
|
Martin Leese wrote:
> I am using PHP version 4.2.3. This is old,
> but I cannot upgrade.
>
> I came across a strange limitation which is
> puzzling me. The following test program:
>
> <?php
> // This PHP file tests the use of count() as an array index
> $anArray[1] = "This is element one";
> $anArray[2] = "This is element two";
> $anArray[3] = "This is the last element";
> //
> echo "$anArray[count($anArray)]\n";
> ?>
>
> produces the error message:
> Parse error: parse error, unexpected T_ENCAPSED_AND_WHITESPACE,
> expecting ']' in CountTest.php on line 7
>
> Why is using count() as an array index not
> allowed?
>
> This is no big deal as the work around is
> trivial; just replace the last line with:
>
> $lastIndex = count($anArray);
> echo "$anArray[$lastIndex]\n";
>
> However, it is puzzling.
You can not use a function call within a quoted string.
You should use:
echo $anArray[count($array)] . "\n";
[Note: in "standard" arrays (indexing starts at 0), count($some_array)
will be an undefined index.]
--
*****************************
Chuck Anderson • Boulder, CO
http://cycletourist.com
Turn Off, Tune Out, Drop In
*****************************
|
|
|