christina
christina

Reputation: 661

Simple PHP Question: Using an IF statement inside a FOR loop

Inside a for loop, I'm trying to set a variable based on the what iteration of the loop it's on:

<?php 
for ($k = 0; $k < 3; $k++){ 
    if ($k = 0) : $var = 'zero';    
    elseif ($k = 1) : $var = 'one'; 
    else : $var = 'two';
    endif;  
?>

This is iteration <?php echo $var; ?>.

<?php }; ?>

But it continues looping forever until my browser freezes... what's going on? Any help would be greatly appreciated!

Upvotes: 0

Views: 17606

Answers (4)

Luis
Luis

Reputation: 1060

for ($k = 0; $k < 3; $k++){ 
    if($k == 0){
        $var = 'zero';
    }elseif($k == 1){
        $var = 'one';
    }else{
        $var = 'two';
    }
}
echo $var;

Upvotes: 1

user912695
user912695

Reputation:

In the if statements, you are using the = operator which assigns...
then $k will always be 0 and the loop will never end. Replace = to == in the if statements. So it will compare instead of assign $k a value.

A clearer example.-

if ($k = 1) // It will return 1, because you are assigning $k, 1.

But in

if ($k == 1) // It will return a boolean **true** if $k equals 1, **false** otherwise.

Upvotes: 1

tskulbru
tskulbru

Reputation: 2346

You are essentially setting $k to be 0 and 1. Comparing values use '=='. Try this instead.

<?php 
for($k = 0; $k < 3; $k++){ 
    if ($k == 0)
        $var = 'zero';    
    elseif ($k == 1)
        $var = 'one'; 
    else
        $var = 'two';  
?>
This is iteration <?php echo $var; ?>.

<?php } ?>

Upvotes: 8

if ($k = 0)

You're setting $k to 0 here. Use == to compare values, or === to compare values and their types.

Upvotes: 1

Related Questions