Using the existing key_exists array

Asked

Viewed 109 times

1

I’m trying to check if any value exists in an array in 1 array I can check if there is more when the array has another array inside I can’t verify if it exists.

1 array

$array = array("Volvo" => 'BMW', "BMW" => 'X5');

array (size=2)
  'Volvo' => string 'XC90' (length=4)
  'BMW' => string 'X5' (length=2)

result of 1 array

if (array_key_exists("Volvo",$array):                           
      echo "existe!";                           
  else :                            
      echo "não existe!";
  endif;

// resultado "existe"

2 array

$array = array(array('volvo' => 'XC90'), array('BMW' => 'X5'));

0 => 
    array (size=1)
      volvo' => string 'XC90' (length=4)
  1 => 
    array (size=1)
      'BMW' => string 'X5' (length=4)

result of 2 array

if (array_key_exists("Volvo",$array):                           
    echo "existe!";                           
else :                            
    echo "não existe!";
endif;


// resultado "não existe"

4 answers

3

This is the expected behavior, there is no "Volvo" key in the initial array. If you have one array within the other (multidimensional array) you should check each array, just make a loop.

When you do:

$array = [['volvo' => 'XC90'], ['BMW' => 'X5']];

It’s the same as doing:

$array = [0 => ['volvo' => 'XC90'], 1 => ['BMW' => 'X5']];

So do: array_key_exists(1, $array); will return true, for these two cases above.


If you want to search the array key within another array you can do:

function multi_array_key_exists($key, array $array) : bool {
    // Pesquisamos no array atual:      
    if (array_key_exists($key, $array)) {
        return true;
    }

    foreach ($array as $v) {    

        // Chamamos a função novamente, para que ele continue a busca no array interno:
        if (is_array($v) && multi_array_key_exists($key, $v)) {
            return true;
        }
    }

    return false;
}
  • thanks for the reply I managed to resolve.

1


Response code in the OSen: Check if specific array key exists in multidimensional array - PHP

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key === $keySearch) {
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}

var_dump(findKey($array, 'Volvo'));

Note: This answer takes into account only if the searched value is equal to the searched.

  • 1

    thanks tested and worked .

  • 1

    And if you search for true? Using loose comparison is quite dangerous in these situations.

  • @Andersoncarloswoss do not agree with enough dangerous, everything depends on the context, maybe the person did not want to test the type and value only the value. It is worth remembering that the answer is withdrawn in the entirety of Soen and placed here exactly giving the proper credibility ... Even not having validity what said I put another one as I know it tests value and type.

  • 1

    Dangerous in the sense of opening gaps for side effects that can be difficult to identify in the application and give maintenance.

1

Hello, the solution to your problem is simpler than it looks. You should create a function that runs through the entire array (using the foreach) and check if that particular index is an array (for this we will use the function is_array), if the checked element is an array it calls the function again by passing that element as the main array. If not, it compares the verified element index to that passed value. See:

function verificaArray($array, $elemento){
    foreach ($array as $key => $value){
        if(!is_array($value)){ // verifica se elemento atual não é um array
            if($key === $elemento){ // se o elemento a ser procurado for igual ao do índice atual
                return true; // Se achou retorna true
            }else{
                end($array);

                if($key === key($array)){
                    return false; // se não acho e estiver no último elemento, retorna falso
                }
            }
        }else{
            return verificaArray ($value, $elemento); // Chama a função para fazer tudo de novo quando é array
        }
    }
}

$a = []; // seu array aqui 

if(verificaArray($a, "Volvo")){
    echo "Existe";
}else{
    echo "Não existe";
}



I hope I helped, hug!

  • Entrance test ['Foo' => 'Bar', 'Volvo' => 1]; even looking for Volvo the exit will be Não existe. In addition to syntax errors, you need to review your return false.

  • when running the code really returns no longer exists with syntax error thought it had worked only that had not saved the code before now saved and gave this error

  • Hello friends, thank you for informing me my mistakes. I believe that have already been corrected. Anyway thanks for making the community better!

1

To search for a given key of a multidimensional array it is necessary to use the recursion and function array_key_exists doesn’t do that.

function array_key_exists_recursive($needle, array $array)
{
    foreach ($array as $key => $value) {
        if ($key === $needle) return $value;
        if (is_array($value)) {
            if ($x = array_key_exists_recursive($key, $value)) return $x;
        }
    }
    return false;
}
  • When you turned this method of some class of yours into function forgot to hit the content of the function by removing the $this of it. Your code the way it is will launch a fatal error Fatal error: Uncaught Error: Using $this when not in object context... 'cause you’re using $this outside the context of a class.

  • Thank you so much for @Vinicius.Silva. I fixed the bug.

  • Even so, there’s no reason to vote no, just say the word!

  • I was trying to scroll the pad of the notebook and ended up generating click and the OS wouldn’t let me remove the downvote (which has already been removed) until you edit the answer.

  • 1

    A very important detail is that the function will not return true when to find, but rather the value found itself, so beware how not to do $resultado === true must be taken.

  • 1

    E @Victorcarnaval, recommend keeping the ===, for with only two it can happen: array_key_exists_recursive(true, ['Volvo' => 'Foo']) return Foo

  • Got it @Andersoncarloswoss, thanks for the explanation.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.