fightstarr20 fightstarr20 - 1 month ago 6
PHP Question

PHP array detect if it contains unique value

I have some PHP arrays that looks like this...

$cars1 = array("Volvo", "Volvo", "Volvo");
$cars2 = array("Volvo", "BMW", "Toyota");
$cars3 = array("Volvo");
$cars4 = array("Volvo", "BMW", "Volvo");
$cars5 = array("BMW", "Toyota");


I need to detect when an array contains all Volvo's or only one Volvo on it's own. So in the examples above only $cars1 and $cars3 would pass.

Anyone have a similar example I can see?

Answer

you're proably looking for something like this

function arrayEq($array,$val)
{
    foreach($array as $item)
    {
        if($item != $val)
        {
            return false;
        }
    }
    return true;
}

$cars1 = array("Volvo", "Volvo", "Volvo");
$cars2 = array("Volvo", "BMW", "Toyota");
$cars3 = array("Volvo");
$cars4 = array("Volvo", "BMW", "Volvo");
$cars5 = array("BMW", "Toyota");

var_dump(arrayEq($cars1,"Volvo"));
var_dump(arrayEq($cars2,"Volvo"));
var_dump(arrayEq($cars3,"Volvo"));
var_dump(arrayEq($cars4,"Volvo"));
var_dump(arrayEq($cars5,"Volvo"));

what the function does is loops though the passed array with a for each and with each item in the array it compares it to the comparing value we passed in.

if even one item in the array doesn't match the comapring value we return false. this breaks out of the loop as well. if the loop can goes all the way though then we know that all the values are the same and return true

note that this is case sensitive ss "Volvo" != "volvo" but you can fix this with something like strtoupper or strtolower

Comments