PHP if condition fails inside a foreach loop

823 views Asked by At
<?php
$key='APS';
$value='A|B|';
if ($key == 'APS'){
    $aps = $key;
    if (!empty($value)){
        if(preg_match("/\|/",$value)){

            $elephant = explode('|',$value);

            foreach ($elephant as $elekey=>$elevalue){
                if($elevalue = 'A'){
                    $elevalue_a=$elevalue;
                    if(isset($aps) && ($aps != '')){
                        if(isset($elevalue_a) && ($elevalue_a != '')){
                            echo $elevalue;
                            echo '<br>';
                        }
                    }
                }
                if($elevalue = 'B'){
                    $elevalue_a=$elevalue;
                    if(isset($aps) && ($aps != '')){
                        if(isset($elevalue_a) && ($elevalue_a != '')){
                            echo $elevalue;
                            echo '<br>';
                        }
                    }
                }
                if($elevalue = 'C'){
                    $elevalue_a=$elevalue;
                    if(isset($aps) && ($aps != '')){
                        if(isset($elevalue_a) && ($elevalue_a != '')){
                            echo $elevalue;
                            echo '<br>';
                        }
                    }
                }
                if($elevalue = 'D'){
                    $elevalue_a=$elevalue;
                    if(isset($aps) && ($aps != '')){
                        if(isset($elevalue_a) && ($elevalue_a != '')){
                            echo $elevalue;
                            echo '<br>';
                        }
                    }
                }
                if($elevalue = 'E'){
                    $elevalue_a=$elevalue;
                    if(isset($aps) && ($aps != '')){
                        if(isset($elevalue_a) && ($elevalue_a != '')){
                            echo $elevalue;
                            echo '<br>';
                        }
                    }
                }
            }
        }
        else{
            echo $singlevalue = $value;
        }
    }
    else {
        echo $value='NIL';
    }
}
?>

The above code may be lengthy but it's a very simple example, where if you execute you can see the if conditions will be failing to escape the loops.

Why in PHP if condition fails inside a foreach loop?

1

There are 1 answers

0
Shankar Narayana Damodaran On BEST ANSWER

The Problem : You are using assignment operator inside if statements

Replace = with == or === (strict check)

if($elevalue = 'B'){

to

if($elevalue == 'B'){  [or] if($elevalue === 'B'){