Prithviraj Mitra
Prithviraj Mitra

Reputation: 11812

Create array from another array if values are same

I have the following array -

Array
(
    [31] => Array
        (
            [0] => 3
            [1] => 3
        )
    [33] => Array
        (
            [0] => 2
            [1] => 1
        )
)

Now for the key 31 both of the elements has same value ie 3 but not for the key 33. So I am trying to create another array which will look like.

Array
(
    [31] =>  same
    [33] =>  notsame       
)

That means if a key from multidimensional array has got all the values same then it will have the text 'same' else 'notsame'

My code-

foreach($subvaluesArr as $k1=>$v1) //$subvaluesArr is the multidimensional array here
    {
        foreach($v1 as $k2=>$v2)
        {           
             if($v1[$k2] = $v1[$k2+1])
            {
                $newArr[$k1] = 'same';
            }
            else
            {
                $newArr[$k1] = 'notsame';
            }
        }
    }

    echo '<pre>';
    print_r($newArr);
    echo '</pre>';

And the output is showing 'notsame' for both keys.

Array
(
    [31] => notsame
    [33] => notsame
)

Any help is highly appreciated.

Upvotes: 1

Views: 29

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

When you run this snippet, you will get this error

Notice: Undefined index: 2 in /in/bcqEH on line 14

See https://3v4l.org/bcqEH

This is because the code tries to compare first and second, and it tries to compare second and third element. But this third element doesn't exist. This means the comparison fails and sets the value to notsame.

To fix this, you could just compare the first two elements, e.g.

foreach ($subvaluesArr as $k1 => $v1) {
    if ($v1[0] == $v1[1]) {
        $newArr[$k1] = 'same';
    } else {
        $newArr[$k1] = 'notsame';
    }
}

When you really have more than two elements, you might try array_unique

foreach ($subvaluesArr as $k1 => $v1) {
    $u = array_unique($v1);
    if (count($u) == 1) {
        $newArr[$k1] = 'same';
    } else {
        $newArr[$k1] = 'notsame';
    }
}

Upvotes: 1

insider
insider

Reputation: 362

cant comment so I write it as answer. In your loop when you hit last element of an array, you ask

if($v1[$k2] == $v1[$k2+1])

where $v1[$k2+1] is "undefined" as you are out of bounds. So this last element is always false and you end up with "notsame"

Upvotes: 0

Ataur Rahman
Ataur Rahman

Reputation: 1791

You have to break; loop after running the if-else condition. example :

foreach($subvaluesArr as $k1=>$v1) //$subvaluesArr is the multidimensional array here
{
    foreach($v1 as $k2=>$v2)
    {           
         if($v1[$k2] === $v1[$k2+1])
        {
            $newArr[$k1] = 'same';
        }
        else
        {
            $newArr[$k1] = 'notsame';
        }
        break;
    }
}

Upvotes: 0

Related Questions