0

I have tried to compare a value to another value in an array. However, the message only displays exits in array 2even when I have two different values (one is 10, the other values from the array are 4 and 6)

if (in_array($post,$orderP)==0){
    echo ' exists in array2';
}else{
    echo 'does not exists in array2';
}

echo $post; //gives a value of 10
echo var_dump ($orderP); 

gives a value of

array(2) { [0]=> array(2) { ["post_ID"]=> string(1) "4" 
                            [0]=> string(1) "4" 
                          } 
            [1]=> array(2) { ["post_ID"]=> string(1) "6" 
                             [0]=> string(1) "6" 
                            } 
        }
3
  • 1
    in_array itself will false or true so no need to check it with ==0 just if(in_array($post, $orderP)){echo 'exists';} is enough Commented Mar 2, 2017 at 2:22
  • @vSugumar ok, I tried to remove the == 0 and apparently it stills display does not exist even though I have a matching value of 4 and array(4) Commented Mar 2, 2017 at 2:31
  • check my below answer and tell me if it helped Commented Mar 2, 2017 at 2:42

2 Answers 2

1

You have multidimensional array, so try something like this

$ids = array_column($orderP, 'post_ID');

if (in_array($post,$ids)){
            echo ' exists in array2';
            }
else{
            echo 'does not exists in array2';
            }
Sign up to request clarification or add additional context in comments.

Comments

0

I dont think in_array will check recursively,,, there may better code.. but my solution is..

$bool = false;
foreach($orderP as $order){

  if (in_array($post,$order)){
     echo ' exists in array2';
     $bool=true;
     return;
  }
}

if(!$bool){

    echo 'does not exists in array2';

}

1 Comment

thanks, it helped me. Both yours and the code above :)

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.