Search code examples
phparrayscomparearray-difference

PHP - how to compare value of arrays in dynamic way?


Ok, I have following 'challange';

I have array like this:

Array
(
    [0] => Array
        (
            [id] => 9
            [status] => 0
        )

    [1] => Array
        (
            [id] => 10
            [status] => 1
        )

    [2] => Array
        (
            [id] => 11
            [status] => 0
        )
)

What I need to do is to check if they all have same [status]. The problem is, that I can have 2 or more (dynamic) arrays inside.

How can I loop / search through them?

array_diff does support multiple arrays to compare, but how to do it? :( Which ever loop I have tried, or my Apache / browser died - or I got completely bogus data back.


Solution

  • Try this code:

    $status1 = $yourArray[0]['status'];
    $count = count($yourArray);
    $ok = true;
    
    for ($i=1; $i<$count; $i++)
    {
      if ($yourArray[$i]['status'] !== $status1)
      {
        $ok = false;
        break;
      }
    }
    
    var_dump($ok);