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;
}
2
  • 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. Commented Feb 10, 2015 at 3:03
  • 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.. Commented Feb 11, 2015 at 8:58
1
for ($i = 1; $i <= 6; $i++)
    $ar[] = $i;
0
 for ($i=1;$i<7;$i++)
 {
      $ar[] = $i;
 }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.