homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

PHP array key issue

5+ Year Member

Msg#: 4463591 posted 2:50 pm on Jun 10, 2012 (gmt 0)

Hi there,

I have the following code accessing values from an associative array:

foreach ($genders[$lang] as $value) {

if($value==true) {

echo key($genders[$lang]);




The key function however only echoes the key name of row 1, it seems to be skipping row 0. The contents of the array are:

Array ( [m] => 1 [f] => 1 [n] => 1 [c] => [mp] => [ma] => [mi] => )

So when I run the above code I get the output "fnc" instead of "mfn". Itís as if the if statement is detecting the correct row but the key function is not.

Iíve tried Googling around this but to no avail, I wonder if any of you guys can help :)




WebmasterWorld Senior Member rocknbil us a WebmasterWorld Top Contributor of All Time 10+ Year Member

Msg#: 4463591 posted 4:18 pm on Jun 11, 2012 (gmt 0)

Generally there's no reason to use next in a for/foreach loop, and may have something to do with it. It's not like a "next" in any other languages, it is used to advance the pointer within the loop (instead of just going to the next item.) It advances the pointer by one (one more than it would in a normal for/foreach.)

You don't need to evaluate true/false, 1/0 if your array values could be empty or null. It is, or it is not, allowing you to try a more simple method:

foreach ($genders[$lang] as $value) {
if($value) {
echo key($genders[$lang]);


Msg#: 4463591 posted 8:43 pm on Jun 11, 2012 (gmt 0)

The use of
next() is what's messing things up. The foreach loop automatically advances to the next element in the array, so there's no need for you to do it "manually".

Note: It's best to be as explicit as possible. Yes,
if( $value == true ) and if( $value ) will work if $value is true, 1, or "1", but it will also "work" if $value is "foo". That's probably not a good thing.

if( $value == true ) should be if( $value === 1 ) (if $value is an actual integer) or, even better, if( 1 === $value ). Getting into the habit of placing the variable on the right means that you avoid this sort of "whoops!" moment: if( $value = 1 ).


Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved