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

Time:09-09

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';
}

CodePudding user response:

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)

CodePudding user response:

return array_search("Jack", $my_array,false)

should work.

For more information about array_search read the php documentation

CodePudding user response:

array_search is doing strict search, I think you can you use strpos() as shown in the example below.

function searchInArray($rawArray, $search, $column) {
    foreach ($rawArray as $value) {
        if (isset($value[$column]) && strpos($value[$column], $search) !== false) {
            return true;
        }
    }
    
    return false;    
}

echo searchInArray($my_array, "Jack", "Description");
  • Related