Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create one variable from multiple variables in PHP? [closed]

Tags:

php

Lets say we have variables: $page and $id. For example, $id=2. I wanna create new variable from existing variables $page and $id: $page2. how to do it? is it possible??

like image 778
Tural Ali Avatar asked Mar 12 '26 11:03

Tural Ali


2 Answers

You can use curly brackets notation to create your variable name : http://codepad.org/L6B5vYdG

 <?php        
       $number = 2;        
       ${'page' . $number} = 20 ;        
       var_dump($page2);        
  ?>
like image 99
DhruvPathak Avatar answered Mar 14 '26 00:03

DhruvPathak


You are asking for variable variables:

$page = 'x';
$id   = 2;

${$page . $id} = 'lol'; // variable is named `$x2`

Or, simpler (I can't quite tell from your question):

$id   = 2;

${'page' . $id} = 'lol'; // variable is named `$page2`

However, this is almost always a bad idea. Prefer arrays and/or objects.

like image 23
Lightness Races in Orbit Avatar answered Mar 14 '26 01:03

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!