I am a newbie about this php stuff. The function below always returns true. Can you explain how this happens? My purpose was to write a general code for searching in a multiarray however I came across this problem and wondered how this can be. Kind Regards.
<?php
function existInMultiArray ($demand, $multiarray)
{
foreach ($multiarray as $key => $val)
{
foreach($val as $key1 => $val1)
{
foreach($val1 as $key2 => $val2)
{
if ($key == $demand)
{
return TRUE;
}
if($key1 == $demand)
{
return TRUE;
}
if ($key2 == $demand)
{
return TRUE;
}
}
}
}
return FALSE;
}
$demand = 'asdf';
$multiarray = array
(
0 => array ('A' => array( 'B' => 'C')),
1 => array ('D' => array ('E' => 'F')),
2 => array ('G' => array ('H' => 'J')),
3 => array ('K' => array ('L' => 'M')),
4 => array ('N' => array ('O' => 'P')),
5 => array ('R' => array ('S' => 'T'))
);
var_dump(existInMultiArray($demand, $multiarray)); exit;
This is because $key, $key1, $key2 have integer datatype and $demand have string datatype. If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
In PHP, the empty string, and the string "0" will both be equal to zero with the equality operator (==).
and in your case, you use === with strict type checking. It means it will check data type as well as value.
<?php
$demand = 'asdf';
$multiarray = array
(
0 => array ('A' => array( 'B' => 'C')),
1 => array ('D' => array ('E' => 'F')),
2 => array ('G' => array ('H' => 'J')),
3 => array ('K' => array ('L' => 'M')),
4 => array ('N' => array ('O' => 'P')),
5 => array ('R' => array ('S' => 'T'))
);
function existInMultiArray ($demand, $multiarray)
{
foreach ($multiarray as $key => $val)
{
foreach($val as $key1 => $val1)
{
foreach($val1 as $key2 => $val2)
{
if ($key === $demand)
{
return TRUE;
}
if($key1 === $demand)
{
return TRUE;
}
if ($key2 === $demand)
{
return TRUE;
}
}
}
}
return FALSE;
}
var_dump(existInMultiArray($demand, $multiarray)); exit;
?>