PHP

Using PHP To Find Value In Array

Arrays are very important concept, be it any programming language. So while working with arrays, there might be a necessity to find a specific value in an array. In this article, I am going to share a very simple yet easy way to use  PHP to find value in array by means of examples.

How to use PHP to Find Value In Array

Let’s assume that we have an array that contains fruits names. Now we would like to find if the value i.e. a specific fruit name exists in our array of fruits. PHP provides us with a very simple function called “array_search”. So “array_search”  searches an array for a given value and returns the corresponding key if they value is successfully found. All of the code is highly commented, so make sure you read each line to understand what each step actually does.

Example 1: By using array_search when array consists of Unique Values

<?php 
//Example 1: Declare an array with unique values===============================================/
$my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple');

//Print the contents of the array. Use the <pre> tags to output the array in readable format.
echo 'Following are the original array contents:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

$key = array_search('grapes', $my_fruits_array);

//Echo the Key of the found value
echo 'The key of the grapes value is: '.$key;

echo '<br /><br />';
?>

Example 2: By using array_search when array consists of Repeated/Duplicate Values

<?php 
//Example 2: Declare an array with duplicate values. We will find index/key of repeated values===/
$my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple', 'grapes');

//Print the contents of the array. Use the <pre> tags to output the array in readable format.
echo 'Following are the array contents with duplicated values:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

//Iterate through all values of our array
foreach( $my_fruits_array as $key => $val )
{
	//If our desireds value is found, then simply store its key in a different array
	if( 'grapes' == $val )
	{
		$all_indices_for_value[] =  $key;
	}
}

echo 'Print all indicies of the values found in array:<br />';
//Print all indicies of the values found in array
echo '<pre>';
print_r($all_indices_for_value);
echo '</pre>';

echo '<br /><br />';
?>

That’s it!
Do you know of any other ways to use  PHP to find value in array? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*