FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Using count() as an array index
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Using count() as an array index [message #178415 is a reply to message #178410] Fri, 15 June 2012 21:38 Go to previous messageGo to previous message
Denis McMahon is currently offline  Denis McMahon
Messages: 634
Registered: September 2010
Karma:
Senior Member
On Fri, 15 Jun 2012 12:51:59 -0600, 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?

What's not allowed is using a function call as part of a variable
translation inside a string.

> This is no big deal as the work around is trivial; just replace the last
> line with:
>
> $lastIndex = count($anArray);
> echo "$anArray[$lastIndex]\n";

Note that by default, array indexes start at 0.

<?php
$arr = array("first","middle","last");
$len = count($arr);
echo "element {$len} is {$arr[$len]}\n";
?>

Generates output:

============
PHP Notice: Undefined offset: 3 in /home/denis/programming/php/
arrcountfail.php on line 4
element 3 is
============

Rgds

Denis McMahon
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: runkit
Next Topic: PHP mysql_excape but need to search for those items
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Mon Nov 25 03:19:38 GMT 2024

Total time taken to generate the page: 0.03935 seconds