PHP – check if a value is in array

Checking if a value exists in array is frequently used in php. PHP in_array() can be used for this check. By default it does not do a strict check. So a string will match with number if same.

in_array without strict

Here string ‘123’ will match with number 123.

<?php
$a = array('abc', 123);
if (in_array('123', $a)) {
  print "FOUND\n";
} else {
  print "NOT_FOUND\n";
}
?>
FOUND
Env: PHP 5.5.9 (Linux)

in_array with strict

Here string ‘123’ will not match with number 123.

<?php
$a = array('abc', 123);
if (in_array('123', $a, TRUE)) {
  print "FOUND\n";
} else {
  print "NOT_FOUND\n";
}
?>
NOT_FOUND
Env: PHP 5.5.9 (Linux)

in_array and associative array

Here in_array only checks in values (not keys).

<?php
$a = array('k1'=>'abc', 'k2'=>123);
if (in_array('abc', $a)) {
  print "FOUND\n";
} else {
  print "NOT_FOUND\n";
}
if (in_array('k1', $a)) {
  print "FOUND\n";
} else {
  print "NOT_FOUND\n";
}
?>
FOUND
NOT_FOUND
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments