Skip to content
Advertisement

How to Use an Outside Variable Inside a For Loop (Scope)

Simple question that I haven’t seen answered anywhere:

How can I use an outside $variable, inside a for loop?

In my PHP code, I have a SplDoubleyLinkedList full of friends names, and I am looping through them one by one to use in an if statement that compares the current friend to the $friend name parameter. How can I change or orient the $idx variable so that it is seen within the loop and if statement?

This is not a question related to SplDoubleyLinkedList, rather it is just to scoping.

<?php

  function removeFriend($friendsList, $friend)
  {
    $idx = null; //how can I set this index variable from the inside of the for loop?
    for ($friendsList->rewind(); $friendsList->valid(); $friendsList->next()) {
      if($friendsList->current() === $friend){
        $idx = $friendsList->key(); //"$idx is declared but not used."
      }
    }
  }

?>

This is a generalized example of my issue:

<?php

function test()
  {
    $test = 0; //how can I set this index variable from the inside of the for loop?
    for ($i = 0; $i < 10; $i++) {
      $test = 1; //"$idx is declared but not used."
    }
  }
  
 ?>

If this exact function is put into a JS file, it does not show this “$idx is declared but not used” warning.

Advertisement

Answer

The answer is simple and is due to the differences between JavaScript and PHP in my VSCode IDE and Intellisence.

IDE: VScode

Intellisence: PHP Intelephence VSCode extension

In PHP: The variable must be at least read to eliminate the warning “$idx is declared but not used.”

In JS: The variable must be either at least written or read to eliminate the warning “$idx is declared but not used.”

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement