Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

Example

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

$hasNeedle = !!$matches;
var_dump($hasNeedle);

Output

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

)


bool(true)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading