Jump to content

Array from for loop?


MikeUK

Recommended Posts

I need some help please.  All the tutorials I've seen tell you how to search an array using a loop, but how do you create an array from the following?

 

for ($a = 0; $a <= 100; $a ++) {

for ($b = 0; $b <= 50; $b ++) {

 

                //Put each value of $b and each value $a into an array

                  $new_array[$a][$b]= $x // Doesn't work!

 

                }

}

 

What I'm trying to do is create an array of all the $a values and $b values and then get an average for each set. Any array I try to create inside the loop is storing only one value. The next iteration is overwriting it like it would a variable.  Any ideas? I'd really appreciate any help.

 

Thanks

Mike

Link to comment
Share on other sites

Declare the array first

<?php
$new_array = array();
for ($a = 0; $a <= 100; $a ++) {   
      for ($b = 0; $b <= 50; $b ++) {

                //Put each value of $b and each value $a into an array
                  $new_array[$a][$b]= $x // Doesn't work!

                }
}

Link to comment
Share on other sites

add ; after $x

<?php
$new_array = array();
for ($a = 0; $a <= 100; $a ++) {   
      for ($b = 0; $b <= 50; $b ++) {

                //Put each value of $b and each value $a into an array
                  $new_array[$a][$b]= $x; // Doesn't work!

                }
}

Link to comment
Share on other sites

oh my. if what you really want to do is "create an array of all the $a values and $b values and then get an average for each set":

 

<?php
$array_a = array();
$array_b = array();
for ($a = 0; $a <= 100; $a ++) {   
$array_a[] = $a;
}

for ($b = 0; $b <= 50; $b ++) {   
$array_b[] = $b;
}

echo "Average of array_a is ".array_sum($array_a)/count($array_a)."<BR>";
echo "Average of array_b is ".array_sum($array_b)/count($array_b)."<BR>";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.