How can I build variable at run time in PHP?

Mostly time we need to create some variables at run time. because we do not want to write same line. For example you have an array like :

$user_details = array(
		'name'	=> 'test1',
		'email'	=> 'test@example.com',
		'phone_number' => '1234567890'
	);

and you want to make run time variable like :

$name = 'test1';
$email = 'test@example.com';
$phone_number = '1234567890';

Mostly developers do this type of mistake:

foreach ( $user_details as $key => $value ) {
	echo "$" . $key  . "=" . $value[0] . '
';
}

It will show :

$name = test1
$email = test@example.com;
$phone_number = 1234567890

But these are not variables because when you try to print $name in the file then it will not show a result.
So for this you can use {} to create run time variables* :

foreach ( $user_details as $key => $value ) {
	echo ${$key} = $value;
}

It will print same output what you want. and also when you print $name, $email or $phone_number then it will print its value.

*Note : $key value must be follow variable naming rules.


Comments

2 responses to “How can I build variable at run time in PHP?”

Leave a Reply

Your email address will not be published. Required fields are marked *

*