Treating array_count_values as an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dark_ixion
Forum Newbie
Posts: 1
Joined: Sun May 25, 2008 6:42 am

Treating array_count_values as an array

Post 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?
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: Treating array_count_values as an array

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Treating array_count_values as an array

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply