PHP Search in Arrays Tutorial with Examples

03-Apr-2023

.

Admin

Hello Friends,

In this blog, I will show you how to search in arrays using PHP, We’ll find out how to search through the arrays in PHP. Working with arrays in php is made simple by its some standard built-in functions like array_search, array_key_exists, keys, and in_array.

Here i will give you full example for all array search function using php So let's see the bellow all example:

Example : array_search()


PHP array_search() is an inbuilt function that searches an array for a value and returns the key. The array_search() function returns the key for value if it is found in the array.

$myArray = ['car', 'bike', 'bus', 'truck'];

$search = array_search('bike', $myArray);

echo $search;

// Output - int(1)

Output

int(1)

Example : array_keys()

The array_keys() function returns an array containing the keys.

$myArray = [

'car' => 'bmw',

'bike' => 'ktm',

'bus' => 'volvo',

'truck' => 'ashok layland'

];

$search = array_keys($myArray, 'volvo');

print_r($search);

// Output - Array ( [0] => bus )

Output

Array ( [0] => bus )

Example : in_array()

The in_array() function searches an array for a specific value. Returns true if needle is found in the array, false otherwise.

$myArray = [

'car' => 'bmw',

'bike' => 'ktm',

'bus' => 'volvo',

'truck' => 'ashok layland'

];

if (in_array("volvo", $myArray))

{

echo "Found the value";

}

else

{

echo "Value doesn't exist";

}

// Output - Found the value

Output

Found the value

Example : array_key_exists()

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

$myArray = [

'car' => 'bmw',

'bike' => 'ktm',

'bus' => 'volvo',

'truck' => 'ashok layland'

];

if (array_key_exists("bus", $myArray))

{

echo "Key exists in array!";

}

else

{

echo "Key doesn't exist in array!";

}

// Output - Key exists in array!

Output

Key exists in array!

It will help you....

#PHP