How to check if a value exists in a multidimensional array?

1

I have the following data coming from a bank:

    array(2) {
  [0]=>
  object(stdClass)#28 (6) {
    ["id"]=>
    string(1) "5"
    ["user"]=>
    string(2) "26"
    ["created_date"]=>
    string(19) "2017-09-29 13:53:38"
    ["first_name"]=>
    string(8) "Gabriela"
    ["last_name"]=>
    string(5) "Silva"
    ["comment"]=>
    string(39) "esse é o comentario para o eeo"
  }
  [1]=>
  object(stdClass)#29 (6) {
    ["id"]=>
    string(1) "1"
    ["user"]=>
    string(1) "1"
    ["created_date"]=>
    string(19) "2017-09-29 00:00:00"
    ["first_name"]=>
    string(8) "Vinicius"
    ["last_name"]=>
    string(6) "Aquino"
    ["comment"]=>
    string(13) "helloooooooo!"
  }
}

How can I check if the "user" 26 exists in this array?

    
asked by anonymous 29.09.2017 / 19:07

3 answers

6

If you're sure how many dimensions are in the case there, apparently from a loop:

foreach($array as $row){
   if($row['user'] == '26'){
      return true;
   }
}

You can also use:

foreach($array as $row){
   if (in_array('26', $array)) {
      return true;
   }
}

You can not use in_array directly in the array just because it is in another dimension, I saw there that I wanted a solution without a loop, to 'play', it is not exactly a gambiarra anymore:

Separate the column, join, and now yes check if it exists:

$users_cods = array_column($array, 'user');

if(in_array('26',$users_cods)){
    return true;
}

There are dozens of ways to do this, but these are the ones I use.

    
29.09.2017 / 19:21
2

@AnthraxisBR's answer already answered, I'll leave one more option:

$needle = "26";
array_map(function($array) use ($needle) { return $array['user'] === $needle;}, $array);
    
29.09.2017 / 20:50
2

Another suggestion I usually use in my projects. Follow my contribution.

<?php

$array = array(
    "user1" => array(
        "user" => "20",
        "dados" => array(),
    ),
    "user2" => array(
        "user" => "22",
        "dados" => array(),
    ),
);

$id = "20";
$coluna = "user";

echo $key = array_search(
    $id,
    array_filter(
        array_combine(
            array_keys($array),
            array_column(
                $array, $coluna
            )
        )
    )
); // user1

$key = array_search(
    '50', // Gerar error
    array_filter(
        array_combine(
            array_keys($array),
            array_column(
                $array, $coluna
            )
        )
    )
); // bool(false)
    
29.09.2017 / 21:04