1

I was trying to create a loop for all the variables on a page to display in one while loop. I couldn't seem to get the variable to output. Here is the code I tried that made the most sense to me:

<?php
$varone = true;
$vartwo = 47;
$varthree = "A little string";

$vars = get_define_vars();

while($loop = $vars){
echo "variable ".$vars;
var_dump($vars;)
}
?>

It would crash one browser and the other it would stay blank. The reason I tried the code this way is because I thought of how I would word a mysql loop and I thought it would work in a similar way. Sorry if this is a newb question.

2
  • Tried to update to have a question. Commented Jan 18, 2018 at 19:17
  • 1
    Blank page is parse error var_dump($vars;) <<< Commented Jan 18, 2018 at 19:22

3 Answers 3

2

You should use something like a foreach() loop...

foreach ($vars  as $name => $var){
   echo "variable ".$name."=";
   var_dump($var);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for! Thank you!
0

Alternatively, I think it might be easier to use an array for this.

$new_array[] = true;
$new_array[] = 47;
$new_array[] = "A little string";

$a=0;
while($new_array[$a]){
    echo "variable ".$a." = ";
    var_dump($new_array[$a]);
    $a++;
}

1 Comment

Yes meanwhile that is true that using an array would work and be easier, I have them on a page that has different variables for different things.
0

The reason I tried the code this way is because I thought of how I would word a mysql loop and I thought it would work in a similar way.

Though I would go with foreach you can use your current code with list and each as many use to fetch from MySQL:

while(list($key, $val) = each($vars)){
    echo "variable $key";
    var_dump($val); //var_dump($vars;) PARSE ERROR check ;
}

However each is deprecated:

Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

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.