1

I have a multidimensional array as follows,

$array1 = Array(
            'id'       => Array(1 => 19, 2 => 47),
            'name'     => Array(1 => 'Alex Paul', 21 => 'sdfs'),
            'category' => Array(1 => 1, 21 => 2)
             );

Also I have an array element

     $res['id'][1]= 47;

I want to check $res['id'][1] is present in $array1 or not. How to solve this issue

1
  • 1
    this looks all to be php, why is javascript tagged? Commented Jan 28, 2014 at 5:23

4 Answers 4

1

Just use in_array function

if(in_array($res['id'][1], $array1['id']))
    echo 'Here';
Sign up to request clarification or add additional context in comments.

Comments

1

You can check using in_array() in php

  if(in_array($res['id'][1],$array1['id'])) {
      echo $res['id'][1] . ' exist in array';
  } else {
     echo 'not exist';

  }

Working Demo

3 Comments

you are just checking in the $array1['id']
If I am think logically, then OP compare with $res['id'][1] which is id so I have not consider whole array and just check with id.
you are right, but the question does not mention comparing with just id,
0

Try like,

   $array1=Array ( 'id' => Array (  1 => 19, 2 => 47 ),
           'name' => Array ( 1 => 'Alex Paul', 21 => 'sdfs' ),
           'category' => Array ( 1 => 1, 21 => 2 ));

   $res['id'][1]= 47;

   if(in_array($res['id'][1], $array1['id']))
     echo 'found';

Comments

0

This checks that $res['id'][1] is present in the whole $array1 or not :

$present = false;
foreach($array1 as $val){
    if(in_array($res['id'][1],$val)) $present = true;
}
echo $present ? "Yes" : "No";

If you just want to check in $array1['id'][1], as the other answers are saying,

it is as simple as this :

echo in_array($res['id'][1],$array1['id'][1]) ? "Yes" : "No" ;

Documentation of in_array()

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.