Search code examples
phpfunctionreturn

How to return variable itself from a PHP functions intead of returning the values?


I have several variables which I define in a helper function (value below). I want to get all those variables from the value function by somehow returning them. How can I do this?

<?php
function value()
{
    $var1 = 1;
    $var2 = 2;
    $var3 = 3;
    $var4 = 4;
    $var5 = 5;

    /*I want to return the variables themselves instead of the value of the 
    variables*/
}
?>

Solution

  • You can put it in an array and then get the array keys. Array keys here refer to your variables in your question.

        function value() {
          $arr = array('var1' => 1, 'var2' => 2, 'var3' => 3);
          return array_keys($arr);
        }
    
    $variables_names = value();
    

    Then loop through the return array which contains only the keys (variables names), not the value.

    foreach ($variables_names as $name) {
      echo $name;
    }