Easy way to search value in a PHP array

In this tutorial, you will learn how can easily search or find a value in a PHP array.

PHP in_array() function

The PHP in_array() function checks the existence of the given value in an array, which means the specified value exists in the array or not.

in_array(value, array, type)
  • value – The value you want to search in the array.
  • array – The array in which you want to find the value.
  • type – It is optional parameter. This parameter takes a boolean value (True) to enable the type checking. Such as – the value should be a string or number, etc.

The in_array function returns TRUE if the value is found in the array, else it will return FALSE.

<?php
$a = [75, 'Hello', '36', 25, 45, 10.2];

var_dump(in_array(25, $a));
bool(true)

in_array() Example with type

<?php
$a = [75, 'Hello', '36', 25, 45, 10.2];

var_dump(in_array(36, $a));

// Checking the type as well
var_dump(in_array(36, $a, True));
var_dump(in_array('36', $a, True));
bool(true) 
bool(false)
bool(true)

This in_array() function won’t work if you want to find a value inside a multidimensional array.

But, it will work if an array inside an array is considered as a value.

<?php
$a = [75, ['Hello', 36], 25, 45, 10.2];

var_dump(in_array(36, $a));

var_dump(in_array(['Hello', 36], $a));
bool(false)
bool(true)

PHP in_array() with multidimensional array

As you know this function does not work with multidimensional-array, but you can achieve this by creating a recursive function.

<?php
function my_in_array($value, $array, $strict = false)
{
    foreach ($array as $item) {

        if (($strict ? $item === $value : $item == $value) || (is_array($item) && my_in_array($value, $item))) {
            return true;
        }
    }

    return false;
}

$a = [75, ['Hello', 36], 25, 45, 10.2];

var_dump(my_in_array(36, $a));
bool(true)

PHP get array key by value

If you want to get the key or index number of any value of an array in PHP, you need to use the array_search() function.

The array_search() function is similar to the in_array() function, but this function returns the key or index number of the value if the value is found in the array, else it will return FALSE.

<?php
//      0        1         2        3
$a = ['PHP', 'Node.Js', 'Python', 'Java'];

var_dump(array_search('Python', $a));

// C++ is not in the array
var_dump(array_search('C++', $a));
int(2)     
bool(false)

Leave a Reply

Your email address will not be published. Required fields are marked *