Skip to content

Instantly share code, notes, and snippets.

@waqasy
Created August 1, 2016 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waqasy/cc3911200658e81f4ed3b41b172781cf to your computer and use it in GitHub Desktop.
Save waqasy/cc3911200658e81f4ed3b41b172781cf to your computer and use it in GitHub Desktop.
Check value exists in array php (Seen on http://abhijitpal.in/check-value-exists-in-array-php/)
/* This function check a array value exists in an indexed array or numeric array */
function indexed_in_array($value, $array){
if (in_array($value, $array))
{
return true;
}
else
{
return false;
}
}
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if(indexed_in_array("Peter", $people)){
echo 'array value exists in an indexed array or numeric array';
}else{
echo 'array value not exists in an indexed array or numeric array';
}
<h2>Check value exists in associative array in PHP</h2>
/* This function check a array value exists in an associative array */
function assoc_in_array($value, $array){
$fliparray = array_flip($array);
if (array_key_exists($value,$fliparray))
{
return true;
}
else
{
return false;
}
}
$age = array("0"=>"Peter", "1"=>"Ben", "2"=>"Joe");
if(assoc_in_array("Ben", $age)){
echo 'array value exists in an associative array';
}else{
echo 'array value not exists in an associative array';
}
<h2>Check value exists in multi dimensional array in PHP</h2>
/* This function check a array value exists in multi dimensional array */
function multi_in_array($value, $array)
{
foreach ($array AS $item)
{
if (!is_array($item))
{
if ($item == $value)
{
return true;
}
continue;
}
if (in_array($value, $item))
{
return true;
}
else if (multi_in_array($value, $item))
{
return true;
}
}
return false;
}
$cars = array(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
if(multi_in_array("BMW", $cars)){
echo 'array value exists in multi dimensional array';
}else{
echo 'array value not exists in multi dimensional array';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment