4

How to check if an array key exist or not array within array?

I need check the user id exist in array, i have below 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 the user id exist or not, i have tried below 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";
            }

        }

any one Please help.

4 Answers 4

1
  foreach ($com_array as $report) {
     if(isset($report['user_id'])){
         echo "Eid found";
     }else{
         echo "id not found";
     }
  }

Try above code, you will get the output.

Sign up to request clarification or add additional context in comments.

Comments

1

Try like this...

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

        }

Comments

0

There is no built in function for multi dimension array. You can make one like:

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

Comments

0

If you are only to check the existence of a key you could do this.

$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";
    }
}

Thanks!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.