0

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!

4 Answers 4

8

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 } ?>
Sign up to request clarification or add additional context in comments.

Comments

1
if ($k = 0)

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

1 Comment

It is good practice to do 0 == $k. Once you get into the habit you will always avoid this problem!
1

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.

Comments

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

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.