2

I am having a problem with my code. I am trying to make an if statement. example:

// 1st statement
if( $day1 && $day2 && day3 == null){
    echo  " A"
}

// 2nd statement
elseif ($day4 && $day5 == null) {
    echo "B"
}

// 3rd statement
elseif($day6 && day7 == null) {
    echo "C"
}
else {
    echo "E"
}

if the first statement is true, the output will be: A since if statement will stop if the first statement equals true, I cannot continue to the second statement result.

what I would like to achieve is that if the 1st 2nd, and 3rd are true the result will be:

A B C

for other condition if 1st and 3rd are true the result will be: A C

and so on.

3 Answers 3

2

To accomplish that, you need to put all of your variables into an array, iterate through them building a string to return.

For example

$arr = array("A" =>$test1, "B" =>$test2, "C" => $test3);

$mystring = "";

foreach ($arr as $key=>$value) {
    if($value) {
        if ($mystring != "")
            $mystring += " ";  // add spacer

        $mystring + = $key;
    }
}

echo $mystring;
Sign up to request clarification or add additional context in comments.

2 Comments

i was trying to use array in my case but it seems too hard for my to understand. thanks for your help. :)
I think the only other way is like what littleibex did. I just like the flexibility of the array to add more items.
0

Do the same thing, but without if..elseif. Use only if conditions. You will need a variable to check whether the last else should be executed or not. For that you can save the output in a variable and check if it is empty:

$msg = '';
//1st statement
if ($day1 && $day2 && day3 == null) {
    $msg .= " A";
}

//2nd statement
if ($day4 && $day5 == null) {
    $msg .= "B";
}

//3rd statement
if ($day6 && day7 == null) {
    $msg .= "C";
}

if (!$msg) {
    echo "E";
} else {
    echo $msg;
}

1 Comment

it works. thank you. but im having problem when executing the 'else' statement. so far im only using 'if' without 'else'. and im planning to make more 'if' for the 'else' result null=false
0

you should not use else for your purpose. try this:

    //1st statement
    if( $day1&&$day2&&day3==null)
    {echo  " A"}

    //2nd statement
    if ($day4&&$day5==null)
    {echo "B"}

    //3rd statement
    if($day6&&day7==null){echo "C"}
else {echo "E"}

otherwise each next condition will work only if previous was FALSE

read about it: http://php.net/manual/en/control-structures.elseif.php

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.