John Davidson

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

0 comments
Message:


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?



My Answer:
You can use variable variables in PHP to achieve this. Here's how you can modify your code to call a variable from a string with the same name:

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

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

$firstWordInArrayName = "cars";
$carType = "ford";

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


In this code, `${$firstWordInArrayName . 'Array'}` creates a variable variable by concatenating the value of `$firstWordInArrayName` with the string 'Array' and then using it as a variable name to access the corresponding array.

Rate this post

4 of 5 based on 4292 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us