Using PHP to Find Elements or Keys in Array

This tutorial shows how to search an array for keys or elements

You can both check for the existence of array elements and key values, functions exists to do both. This tutorial shows how to search through an array for a given element or key value.

To check if an element exists in an array, you can use php in array functions. The php in_array function will either return true, if a string was found in the array, or false if it was not found.

When checking if something is in an array this way, the key value of the found element will not be returned – but more on that later – the below example shows how to use the in_array function:

<?php
$aMyTest = array("MyTest1", "MyTest2", "MyTest3", "MyTest4");

if (in_array("MyTest2", $aMyTest)) {
    echo "Found MyTest2" . "<br>";
}
if (in_array("MyTest5", $aMyTest)) {
    echo "Found MyTest5";
} else {
    echo "MyTest5 not found in array!";
}
?>

How to return the key of a found element

If anything has been found, you also sometimes want to know the key value of the array element. To get the key of the element, the PHP array_search function may be used instead of php in array. The next example demonstrates the use of the php array search function.

The difference between this example, and the last, is that we are creating the array in a more readable manner – it doesn't matter how you create the array – and its only for educational purposes anyway.

<?php
$aMyTest['0'] = 'red';
$aMyTest['1'] = 'green';
$aMyTest['2'] = 'blue';

$key = array_search('green', $aMyTest); // Result is key 1
echo $key;
?>

Search for Array keys in PHP

If you are trying to find key values of array elements, the php array_key_exists function may be used. The key value can be anything valid as an array index.

<?php
$aMyTest = array("red", "green", "blue", "black");

if (array_key_exists(3, $aMyTest)) {
 echo 'Found';
} else {
 echo 'Not Found';
}
?>

Another easy way to check if an array key exists, is to use isset() – but this will not return true for array keys containing a NULL value.

<?php
$aMyTest['0'] = 'red';
$aMyTest['1'] = 'green';
$aMyTest['2'] = 'blue';
$aMyTest['3'] = 'black';

if (isset($aMyTest["4"])) {
 echo 'Found';
} else {
 echo 'Not Found';
}
?>

More PHP Array Tutorials

  1. Determine the Length of an Array
  2. How to Loop Through an Array
  3. Create an Array From a List of Keywords with Explode
  4. Get Array Key and Value in PHP Foreach