-4

I have

$string = "temp";

I want extract string value and make new variable (array) :

$temp = array();

is possible?

3
  • You are looking for Variable variables Commented Mar 9, 2016 at 13:54
  • Use this $temp[]=$string; then print $temp with print_r($temp); You will get result of $temp array with value. Commented Mar 9, 2016 at 13:55
  • @SanjayChaudhari, just to make it clear and for future reference, $temp[] = $string; will create an array named $temp with the content of $string on next position (in this case, probably 0). It's not the same as creating a variable where it's name is informed as string in another variable. Take a loot at the result of what you suggested: https://3v4l.org/Mmo5F. Take a look at the expected: https://3v4l.org/U4qWv Commented Mar 9, 2016 at 15:35

3 Answers 3

2

Sure you can!

${$string}

then you can call it like this: $temp;

more information: http://php.net/manual/en/language.variables.variable.php

With this method you can use it in a for loop to create a bunch of variables in no time :)

exemple: ${'box_'.$i.'_image};

Sign up to request clarification or add additional context in comments.

1 Comment

I know it's just to show your point, but note: if you know that you can call it like $temp, why not use it like so from the beginning? You should continue using ${$string} everywhere...
0

You can use Variable variables.

Example:

$string = "temp";
$$string = array();
var_dump($temp);
var_dump($$string);//Same as var_dump($temp)

However I find this can lead to difficult to read code, there is usually other ways to do what you are needing.

2 Comments

var_dump($$string); ;)
@FirstOne Good point! Have added that too.
0

You can just use Variable variables:

$string = "temp";
$$string = array();

More information at http://php.net/manual/en/language.variables.variable.php.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.