Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php string name as variable

Tags:

php


$string = "id";

want result to be like 

$id = "new value";

How do I code this in php?

Edit..

How about the below?


$column = array("id","name","value");

let say found 3 row from mysql

want result to be like this

$id[0] = "3";
$id[1] = "6";
$id[2] = "10";

$name[0] = "a";
$name[1] = "b";
$name[2] = "c";

$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";


like image 869
Paisal Avatar asked Dec 09 '22 11:12

Paisal


2 Answers

Theres 2 main methods

The first is the double $ (Variable Variable) like so

$var = "hello";
$$var = "world";
echo $hello; //world

//You can even add more Dollar Signs

$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a

$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World

//... and so on ...//

@source

And the second method is to use the {} lik so

$var = "hello";
${$var} = "world";
echo $hello;

You can also do:

${"this is a test"} = "works";
echo ${"this is a test"}; //Works

I had a play about with this on streamline objects a few weeks back and got some interesting results

$Database->Select->{"user id"}->From->Users->Where->User_id($id)->And->{"something > 23"};
like image 80
RobertPitt Avatar answered Dec 20 '22 14:12

RobertPitt


You are looking for Variable Variables

$$string = "new value";

will let you call

echo $id; // new value

Later in your script

like image 22
Alan Whitelaw Avatar answered Dec 20 '22 14:12

Alan Whitelaw