Check value exists in array php

Hi friends, today I am coming with another post how to check value exists in array in PHP. When we put some value in a array, we need to check the value already exists in the array. For solving this types of problem I create three functions for three types of array (Indexed array, Associative arrays, Multidimensional arrays). Using my code you can easily check a value exists in an array.

Check value exists in numeric array in 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';
}

Check value exists in associative array in PHP

/* 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'; }

Check value exists in multi dimensional array in PHP

/* 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'; }

Now you know how to check value exists in array. If you find this article useful, do share it on Facebook, Google plus and Twitter. If you have any questions regarding this article, feel free to ask via comment.

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •