0

I have created a multidimensional array which looks like this:

Array
(
[0] => Array
    (
        [id] => 4
        [questions] => Array
            (
                [title] => This is an example
            )

    )

Now I would like to check if there is a value in this array for key "title". I tried it this way but it still returns false:

$key = array_search($value, array_column($array, 'title'));
// value has the value of the title and $array is the multidimensional array
if ($key !== FALSE){
   echo "Found";
} 
else {
   echo "Not found";
}
JavaForAndroid
  • 1,111
  • 2
  • 20
  • 42
  • _key_ and _value_ have special meaning in arrays. What do you mean exactly when you say, 'I would like to check if there is a value in this array for key "title"'? Do you mean you want to check if the key 'title' exists, or that it exists and has a specific value 'This is an example', or something else? – waterloomatt Feb 18 '22 at 14:59
  • Yes, I would like to check if the key exists and has a specific value. Might it be a problem that the string contains umlauts (like ä,ü,ö)? – JavaForAndroid Feb 18 '22 at 15:02
  • Does this answer your question? [Search for a key in an array, recursively](https://stackoverflow.com/questions/3975585/search-for-a-key-in-an-array-recursively) – Nico Haase Feb 18 '22 at 15:50

1 Answers1

1

There are many ways to do it. For example :

foreach ($array as $data) {
    if (isset($data['questions']['title'])) {
        echo 'found';
    }
    else {
        echo 'not found';
    }
}

If you want something reusable, maybe you can put a function inside another one ? Like that :

function search($myarray, $mykey) {
    foreach ($myarray as $key => $value) {
        if (is_array($value)) {
            search($value, $mykey);
        }
        else {
            if ($key == $mykey) {
                echo 'found ';
                if ($value != null) {
                    echo 'and value of '.$mykey.' is '.$value;
                }
                else {
                    echo 'and value is null';
                }
            }
        }
    }
};

search($yourarray, 'title');
Menryck
  • 149
  • 1
  • 9