Search code examples
phpvariables

How to call a variable from a string with the same name? PHP


I have a number of arrays like so:

$fruitArray = array(
 "orange" => "orange",
 "banana" => "yellow",
 "apple" => "green"
);

$carsArray = array(
 "ford" => array (
   "truck" => "big",
   "car" => "small"
 ),
 "mazda" => "yellow",
 "toyota" => "green"
);

Normally I could just use var_dump($carsArray[ford]) but I don't know which parts I need. But I can get the names from other variables. For example,

$firstWordInArrayName = cars;
$carType = ford;

I want to create a variable that allows me to access the a specific array like so:

$variableToCallArrayName = '$' . $firstWordInArrayName . 'Array[' . $cartype . ']';
var_dump($variableToCallArrayName)

Is this a good way of doing this or is there some other way of doing this? And if it is okay, how do I do it please?


Solution

  • You can do it using a variable variables syntax:

    $variableToCallArrayName = ${$firstWordInArrayName . 'Array'}[$cartype];
    
    var_dump($variableToCallArrayName);