1

Is there a short way to write this? Like below:

<?php

$true=1;
$false=0;

$valid = array (
                "part1" => $true,
                "part2" => $true,
                "part3" => $true
);

if($valid == $true){
echo "All the values are True!";
}else{
echo "At list one of the values is False";
}

?>

Instead of this:

 <?php

    if($valid['part1'] == $true && $valid['part2'] == $true && $valid['part3'] == $true{
    echo "All the values are True!";
    }else{
    echo "At list one of the values is False";
    }

    ?>

I have tried writing it as showed in the first example but it doesn't work

4
  • if (count(array_filter($valid)) == count($valid)) { echo 'All the values are Truthy'; } else { echo 'at least one of the values is falsey'; } Commented Aug 25, 2015 at 17:24
  • array_filter is probably slower than the array_unique answer below. Commented Aug 25, 2015 at 17:26
  • @mark use array_unique and equal it to 1 will make the code much faster and much less code is used in general Commented Aug 25, 2015 at 17:26
  • @QuakeCore gave the best answer though must admit i didnt see that approach Commented Aug 25, 2015 at 17:28

4 Answers 4

4
if(!in_array($false,$valid){
echo "All the values are True!";
}else{
echo "At list one of the values is False";
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_keys' second option to search for values matching your variable, and compare the number of results against the total number of elements in your array:

if (count(array_keys($valid, $true)) == count($valid)) {
    echo "All the values are True!";
} else {
    echo "At leastone of the values is False";
}

Comments

0

its an array not a variable you cant just === it

you will have to use

if (count(array_unique($allvalues)) === 1 && end($allvalues) === 'true') {
echo "All the values are True!";
}else{
echo "At list one of tha values is false";
}

Comments

0

You can do this with that:

$array = array(
    'key1' => true,
    'key2' => true,
    'key3' => true,
);

$status = true;
foreach($array as $key => $value) {
    if(!$value) {
        $status = false;
        break;
    }
}
if($status) {
    echo "All the values are True!";
}
else {
    echo "At list one of the values is False";
}

2 Comments

not the best approach given you are skipping out on opportunities to do this way more efficiently. but this is still another approach to it
@BuddhiAbeyratne - True. After my post, I have see the others awnsers with in_array() and array_keys() but I like my way to to it. Always good to know how to do it without specials functions.

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.