Here is some code I have: (p just echos plus adds a newline)
foreach ($vanSteps as $k => $reqInfo)
{
p($k);
if ('van' == $k) { p('The key is the van, continue'); continue; }//continue if we reached the part of the array where van is key
//do stuff
}
and I'm getting this output:
0
The key is the van, continue
1
2
3
van
The key is the van, continue
Why does the if statement return true when the key is 0? This foreach loop handles logic that applies when the key == 0 (and any other key except if the key is 'van') and this messes up the logic because it's return true when key is 0.
Any help?
Thank you.
The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Your answer Declare the $items array outside the loop and use $items[] to add items to the array: $items = array(); foreach($group_membership as $username) { $items[] = $username; } print_r($items); Hope it helps!!
The foreach loop is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to $value, and the array pointer is advanced by one to go the next element in the array. Syntax: <?
Use ===
for this comparison. When PHP compares string and integer it first casts string to integer value and then does comparison.
See Comparison Operators in manual.
In PHP 'van' == 0
is true
. This is because when using ==
to compare a string and a number, the string is converted to a number (as described in the second link below); this makes the comparison internally become 0 == 0
which is of course true
.
The suggested alternative for your needs, would be to use a strict equality comparison using ===
.
See Comparison Operators and String conversion to numbers
In PHP, when you compare 2 types, it has to convert them to the same type. In your case, you compare string
with int
.
Internally this gets converted to
if((int)'van'==0)....
and then
if((int)'van'==1)....
(int)'any possible string' will be 0
:) So you either have to manually convert the both values to the same type, or use ===
as a comparison operator, instead of the loose =
.
An exception from this rule(as pointed out in the comments) would be if the string start with a number, or can be interpreted as a number in any way(1, 0002, -1 etc). In this case, the string would be interpreted as a number, diregarding the end of the non-numeric end-of-string
Take a look at http://php.net/manual/en/types.comparisons.php for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With