Why in_array not work on array that create from loop php ?
this below code show Match found.
<?php
for ($i = 0; $i < 10; ++$i) {
    $people[] = $i;
}    
if (in_array('test', $people))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>
and this below code show Match not found.
<?php
$people = array("0","1","2","3","4","5","6","7","8","9");
if (in_array('test', $people))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>
How to solve first code to show Match not found
Because in your first array you have integers and by default in_array() does a non-strict type comparison, which has only a limited amount of type pairs which it takes into consideration. So it will do a silent cast to an integer with your needle, which results in 0 and it finds it in the array.
To avoid this error, just pass TRUE as 3rd argument to in_array() so it does a strict type comparison, e.g.
if (in_array('test', $people, TRUE))
                        You just change
$people[] = $i; ---by--> $people[] = "$i";
Then you compare strings
<?php
for ($i = 0; $i < 10; ++$i) {
    $people[] = "$i";
}   
if (in_array('test', $people))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>
                        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