Search code examples
phpvariables

How transform a string into a variable name - PHP?


I have a php file ("gion.php") with inside an array:

 $gion = array('ok');

I want to include this file and print the array.

 $name_user = "gion";
 include "profili/".$name_user.".php";
 $file_profile= "$".$name_user;

 print_r($file_profile);

print_r doesn't work because i suspect $file_profile is a string, so i can change it in a name variable ?

"$gion" (string) -> $gion (variable) 

thanks a lot

EDIT: i want to print array('ok') and not "gion"


Solution

  • File: gion.php:

    $gion = array('ok');
    

    File: main.php (or whatever your filename is):

    $name_user = "gion";
    include "profili/" . $name_user . ".php";
    $file_profile = ${$name_user};
    
    print_r($file_profile);   // this also works: print_r($gion);
    

    This will print:

    Array
    (
        [0] => ok
    )