Page 1 of 1

Treating array_count_values as an array

Posted: Sun May 25, 2008 6:46 am
by dark_ixion
I'm having trouble understanding why I can't treat a function which returns an array as an array.

Take the following example

Code: Select all

$names = array("dan", "david", "john", "dan", "clive", "david", "david", "steve");
$namecount = array_count_values($names)["david"];
print "<p>David appears $namecount times.</p>"; 
This produces the error "Parse error: syntax error, unexpected '[' in /var/www/test.php on line XX"

Yet if I adjust it to say...

Code: Select all

$names = array("dan", "david", "john", "dan", "clive", "david", "david", "steve");
$namecountarray = array_count_values($names);
$namecount = $namecountarray["david"];
print "<p>The name david appears $namecount times.</p>"; 
Why is this the case?

Re: Treating array_count_values as an array

Posted: Sun May 25, 2008 9:18 am
by yacahuma
I found a note in php.net saying that

Using variables as array names no longer works in PHP5

I have no idea if this is a bug. One solution will be to use eval. I suggest just using the code that works.

Re: Treating array_count_values as an array

Posted: Mon May 26, 2008 10:34 am
by pickle
In your first example, you can't reference an array element that way. I don't know exactly how to describe why you can't, I just know you can't.