Enes Altuntas
Enes Altuntas

Reputation: 13

Checking the equality of all values in array in php

I check the equality of all values in the array in php this way. I could not find how to do this on any web page, if there is an easier method you can write.

    $array = array(2, 2, 1);

    $first_value   = $array[0];
    $count_invoice = count($array);

    $i = 0;
    foreach ($array as $item) {
        if ($item == $first_value) {
            $i++;
        } else {
            // Not equal.
        }
    }

    if ($i == $count_invoice) {
        echo "Array equal.";
    } else {
        echo "Array not equal.";
    }

Upvotes: 1

Views: 59

Answers (2)

Ro Achterberg
Ro Achterberg

Reputation: 2694

Good job on finding a solution yourself. However, your code is a little convoluted and might be simplified. I understand you don't have an actual question, but you may find my suggested improvement useful anyway.

<?php

// Your input array.
$array = array(2, 1, 1);
// Another array, which consists of unique elements.
$uniqueArray = array(1, 1, 1);

// Use array_unique() to remove duplicates, and count the results. If there is more than one value, then the array didn't consist of all unique values.
var_dump(count(array_unique($array)) === 1); // FALSE
var_dump(count(array_unique($uniqueArray)) === 1); // TRUE

Upvotes: 1

u_mulder
u_mulder

Reputation: 54831

There's no need to count anything. As soon as you see the value, which not equals $first_value, you can break the loop:

$array = array(2, 2, 2);
$first_value   = array_shift($array);
$allEquals = true;
foreach ($array as $item) {
    if ($item != $first_value) {
        $allEquals = false;
        break;
    }
}

if ($allEquals) {
    echo "Array equal.";
} else {
    echo "Array not equal.";
}

Upvotes: 1

Related Questions