1

PHP How to create array value using for loop ?

$my_array=array(
   for ($i=0;$i<10;$i++)
      {
         $i,
      }
);

echo '<pre>'; print_r($my_array); echo '<pre/>';
1
  • why dont you try the range(1,10) ? Commented Feb 18, 2014 at 7:03

4 Answers 4

5

Simple for number arrays.

$my_array = range(0, 10);

If you want to add increment more then 1 you can

$step = 2;
$my_array = range(0, 10, $step);

See here

Sign up to request clarification or add additional context in comments.

Comments

2
$my_array=array();
for ($i=0;$i<10;$i++){
$my_array[]=$i;
}
echo '<pre>';
print_r($my_array);

Comments

0
$my_array = array();
for ($i=0;$i<10;$i++){
            $my_array[]= $i;
}

1 Comment

Please also explain the code you are throwing around.
0

Put the loop after the array declaration

<?php
$my_array=array();
for ($i=0;$i<10;$i++)
{
   $my_array[] = $i;
}
echo '<pre>'; print_r($my_array); echo '<pre/>';
?>

Comments

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.