Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in_array doesn't work on array that was created using loop in PHP?

Tags:

arrays

php

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

like image 988
mongmong seesee Avatar asked Jan 06 '16 04:01

mongmong seesee


2 Answers

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))
like image 75
Rizier123 Avatar answered Oct 03 '22 11:10

Rizier123


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";
  }
?>
like image 27
Rodney Salcedo Avatar answered Oct 03 '22 12:10

Rodney Salcedo