Search code examples
phpvariablescode-snippets

How can we use $1, $2 and vise versa?


Actually I want to get values of array in different variables, so I made this code:

$count = count( $t );
$count = $count - 1;//count starts with 1 and array starts with 0

for ($i=0; $i <= $count; $i++) { 
    $$i = $t[$i];//$0 = something; $2 = something; vise versa
}
// $i = 1;
// $i++;
// $$i = $2;
var_dump($1,$2,$3);

I can create this variables but cannot access them as $1 is not recognized as variables.

Parse error: syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' in C:\xampp\htdocs\stackoverflow\test.php on line 56

I want to use $0, $1, $2, etc.


Solution

  • Not sure about what you are trying to achieve, but it can be done like this:

    $number = 1;
    $$number = 'OK';
    
    echo ${1};
    

    Will output:

    OK