0

How to create array from variable php using loop for ?

i have many variable php like

$number_0 = 1;
$number_1 = 2;
$number_2 = 5;
$number_3 = 2;
$number_4 = 6;

i want to create array like this

$ar = array('1','2','5','2','6');

but using loop for like

for ($i=0;$i<5;$i++)
{
$number."_".$i ====> to array
}

3 Answers 3

7

Not a recomended way of doing things but:

$arr = array();
for($i=0;$i<5;$i++) {
    $varName = 'number_'.$i;
    $arr[] = $$varName;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I was about to ask a similar question, can you explain why it's not recommended, The only variance in my question is that I might add new Variables and I don't want to change numbers every time I would like PHP to detect the number of variables.
variable variable names are not a good practice, generally there is always a better way of doing something than with variable-variables, but very very rarely there isn't..
1
for ($i = 1; $i <= 6; $i++)
    $ar[] = $i;

Comments

0
 for ($i=1;$i<7;$i++)
 {
      $ar[] = $i;
 }

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.