How to check that all the values of an array are equal php? I have been trying with the following code:
$array = "1,1,1,2,1";
$array = explode(",",$array);
$val = 2;
foreach($array as $value) {
if($value=="3") {
$val = "3";
} elseif($value=="1") {
$val = "1";
} elseif($value=="0") {
$val = "1";
} elseif($value=="5") {
$val = "1";
}
}
return $val;
What I try to do:
- If all the values of the array are equal to 1, it returns 1.
- If the numbers 1,2,5,0 are present in the array, it returns 1.
- If all the values of the array are equal to 5, it returns 2.
- If all the values of the array are equal to 0, it returns 0.
- If any value of the array is equal to 3, it returns 3.
contar
The presence of the values of the array occurs to me , to then verify what is the value to return.If none of the conditions are met, return
-1
to default.At the end it prints
-1
for that arrayexampleYou can use
array_unique
to reduce your arrayto non-repeated values, andcount
check how many elements the new has array, if it is 1 you check the value and if it is greater you check the conditions for different values.