Smilie
Smilie

Reputation: 13

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.

Upvotes: 1

Views: 5880

Answers (4)

ComFreek
ComFreek

Reputation: 29424

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

Upvotes: 1

Jasper
Jasper

Reputation: 76003

I'm not sure what you want as output but you could iterate through the outer array and create an output array that groups the inner arrays by status:

$outputArray = array();
foreach ($outerArray as $an_array) {
    $outputArray[$an_array['status']][] = $an_array['id'];
}

Upvotes: 0

Decent Dabbler
Decent Dabbler

Reputation: 22773

function allTheSameStatus( $data )
{
    $prefStatus = null;
    foreach( $data as $array )
    {
        if( $prefStatus === null )
        {
            $prefStatus = $array[ 'status' ];
            continue;
        }

        if( $prefStatus != $array[ 'status' ] )
        {
            return false;
        }
    }

    return true;
}

Upvotes: 1

hakre
hakre

Reputation: 197795

You could just put the problem apart to make it easier to solve.

First get all status items from your array:

$status = array();
forach($array as $value)
{
    $status[] = $value['status'];
}

You now have an array called $status you can see if it consists of the same value always, or if it has multiple values:

$count = array_count_values($status);
echo count($count); # number of different item values.

Upvotes: 2

Related Questions