0

Hello everyone I am stuck in php functions I am not getting the variable data outside from the function in php as i am new in php so please don't refer me to any other question thank you my code is.

<?php

function variables()
{
    $var = rand(1111,9999);
    $var2 = rand(11111,99999);
    $var3 = rand(111111,999999);
}
echo variables([$var]);
echo variables([$var2]);
echo variables([$var3]);

?>

2 Answers2

1

since the variables '$var','$var2' and '$var3' are local variable for the function variables so it has no existence unless the function is called or executed.

So there are two methods to fix your issue

  1. Method one make the variable global.

      <?php
      // Declaring the global veriable
      $var=0;
      $var2=0;
      $var3=0;
    
      function variables()
      { // method 2 to declare global
       GLOBAL $var = rand(1111,9999);
       GLOBAL $var2 = rand(11111,99999);
       GLOBAL $var3 = rand(111111,999999);
      }
    

but still, if u want to get the rand value from the function u need to call the function at least once

     // calling the function
     variables();
     echo variables([$var]);
     echo variables([$var2]);
     echo variables([$var3]);

     ?>

hope you got the solution if not just comment I will help u out with this for sure

Rahul Kumar Jha
  • 289
  • 1
  • 8
1

You also can implement parameters by reference.

$var_1 = 0;
$var_2 = 0;
$var_3 = 0;

function variables(&$a, &$b, &$c)
{
    $a= rand(1111,9999);
    $b= rand(11111,99999);
    $c= rand(111111,999999);
}

variables($var_1,$var_2,$var_3);
var_dump($var_1,$var_2,$var_3);

Maybe is better implement a return statement.

        function variables()
        {
            $a= rand(1111,9999);
            $b= rand(11111,99999);
            $c= rand(111111,999999);

            return [$a,$b,$c];
        }
        
        [$var_1, $var_2,$var_3]= variables();
        var_dump($var_1,$var_2,$var_3);