skip to Main Content

Below is my array :

$my_value_is = Array ( [2] => Array ( [id] => 2 [price] => 23) [50] => Array ( [id] => 50 [price] => 56 ) )

$my_var = 56;

I need it to return true if all columns ( price ) match that given variable value; otherwise, it should return false.

hence as per my $my_var, i should get result as false, because id:2 has price:23 which is not matching.

I tried in_array function, but that wont work :

$u_in_array = in_array($my_var, array_column($my_value_is , 'price'));
if($u_in_array ) {
    echo 'value is true';
 } else {
    echo 'value is false';
 }

but it giving me as value is true , where as i need value is false.

3

Answers


  1. The problem is that you are currently looking to see if any of the values match (in_array), so it doesn’t care that some don’t match as long as 1 value does.

    There are a couple of ways of doing this.

    Firstly by just using a foreach over the array and stopping as soon as one doesn’t match…

    $u_in_array = true;
    foreach ($my_value_is as $element) {
        if ($element['price'] != $my_var) {
            $u_in_array = false;
            break;
        }
    }
    
    if ($u_in_array) {
        echo 'value is true';
    } else {
        echo 'value is false';
    }
    

    which looks longer, but can be simpler to modify if needed.

    If you want to use the array_ functions, you can filter the ones matching and then check if the result is empty, if it’s empty – all match…

    $notMatch = array_filter($my_value_is, fn($element) => $element['price'] == $my_var);
    
    if (empty($notMatch)) {
        echo 'value is true';
    } else {
        echo 'value is false';
    }
    
    Login or Signup to reply.
  2. You can use array_diff to check if any value is different in the first array than the second.

    The in_array will only check for first occurrence and will return true immediately if it does.

    <?php
    
    $u_in_array = array_diff(array_column($my_value_is , 'price'), [$my_var]);
    
    if(empty($u_in_array)){
      echo 'value is true';
    }else{
      echo 'value is false';
    }
    
    Login or Signup to reply.
  3. After you extracted the price values using array_column, you can simply create an array of only unique values from that. If the count of elements that contains is exactly one, and that first element matches your target price – then the check is passed, otherwise not.

    function check_all_prices($array, $targetPrice) {
      $test = array_unique(array_column($array, 'price'));
      return count($test) === 1 && $test[0] === $targetPrice;    
    }
    
    var_dump(check_all_prices($my_value_is, $my_var));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search