0

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?

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Use array_unique() function followed by a simple if condition, like this:

$cars1 = array("Volvo", "Volvo", "Volvo");
$car = array_unique($cars1);

if(count($car) == 1 && $car[0] == 'Volvo'){
    // the condition has passed
    // Only $cars1 and $cars3 would get through this if condition
}

// like this, apply the same procedure for other arrays

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.