Problem with mixed array skipping entry 0

Hi.
I’ve been doing self-taught PHP coding for over a year, and this is a new issue for me…

I have an array that looks similar to this:
[php]$myArray[‘general’] = ‘general information’;
$myArray[] = ‘more information 1’;
$myArray[] = ‘more information 2’;
$myArray[] = ‘more information 3’;
$myArray[] = ‘more information 4’;
[/php]

So I should have $myArray[‘general’] and then $myArray[0], etc.

When I read it out, I want the loop to skip the ‘general’ entry, so here’s a simplified version of the code I use:

[php]foreach ($myArray AS $key=>$value)
{
if ($key == ‘general’)
continue;
// do something with every entry that is not ‘general’
}[/php]

The weird thing is that with the line that is meant to skip ‘general’, it also skips the entry 0…

Is that normal? Is this just something that I in my lack of proper education did not know?

I found a workaround for now, but I’m still very curious about why this is not working…

Thanks in advance!

I believe what happens is - PHP interpret your 0 index as numeric type and when it try to compare this index with the string constant ‘general’, it converts string to numeric value (which is 0). To avoid problems with variable types conversions, use === operator instead of ==
Like this:
[php]if ($key === ‘general’)
continue;[/php]

Thanks, that’s exactly what I needed to hear :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service