How to check array key in multidimensional array?

How to check for the presence or absence of an array in an array?

I need to check the user id in the array, I have an array found,

 Array
(

  [0] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 4000
    )

[1] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 0
    )

[2] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 4000
    )

[3] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 0
    )

[4] => Array
    (
        [user_id] => 1483096072
        [week] => 1
        [type] => 1
        [commission] => 4000
    )

[5] => Array
    (
        [user_id] => 1483333245
        [week] => 1
        [type] => 1
        [commission] => 2000
    )

)

I want to check if user id exists or not, I tried under code

        foreach ($com_array as $report) {

         $user_id=$report['user_id'];

        if(array_key_exists($user_id,$output_array)){
                echo "Eid found";
         }else{
                echo "id not found";
            }

        }

anyone please help.

+4
source share
4 answers
  foreach ($com_array as $report) {
     if(isset($report['user_id'])){
         echo "Eid found";
     }else{
         echo "id not found";
     }
  }

Try the code above, you will get the result.

+1
source

Try it...

foreach ($com_array as $key=>$value) {
        if(array_key_exists("user_id",$value)){
                echo "id found";
         }else{
                echo "id not found";
            }

        }
+1
source

There is no built-in function for a multidimensional array. You can do the following:

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            echo 'yes, it exists';
            return true;
        }
        else {
            if (is_array($item) && findKey($item, $keySearch)) {
               return true;
            }
        }
    }

    return false;
}
0
source

If you want to check for a key, you can do it.

$user_id_arr = array_column($output_array, 'user_id'); // Get your user_id to a single dimension array
foreach ($com_array as $report) {
    if ( in_array($report['user_id'], $user_id_arr) ){
        echo "ID Found";
    } else {
        echo "ID Not Found";
    }
}

Thank!

0
source

Source: https://habr.com/ru/post/1666683/


All Articles