PHP: Check if multi dimensional array contains part of a value

Consider an array like this:

$my_array = array(    
    0 =>  array(  
        "Date"   => "20220901",  
        "Description"   => "My name is Jack"  
    1   =>  array(  
        "Date"   => "20220901",  
        "Description"   => "I have a dog"
    2   =>  array(  
        "Date" =>  "20220901",  
        "Description"   => "I have a house"

How do I return true or false if I search for the value ‘Jack’. In other words, how do I search for the word Jack in the array and return true or false if it exists? Remember, ‘Jack’ is just a part of the value and not the full value i.e. ‘My name is Jack’.

This is what I tried but it’s returning false because I didn’t supply the full value:

if (array_search("Jack", array_column($my_array, 'Description')) !== false) {
  echo 'True';
} else {
  echo 'False';

>Solution :

Here is a way to use array_filter to find all matching entries.
To make it a bool you can prefix !!.

You also can use

if ($matches) { doSomething(); } else { echo "Empty"; }

instead of

if (!!$matches) { doSomething(); } else { echo "Empty"; }

This has the advantage, that you also can count the results which is one for this example below.

echo count($matches);


$needle = 'Jack';
$matches = array_filter($my_array, fn($item) => false !== strpos($item['Description'], $needle));

$hasNeedle = !!$matches;


    [0] => Array
            [Date] => 20220901
            [Description] => My name is Jack



Leave a Reply