Jump to content

LOOP and ARRAY


madmhan84

Recommended Posts

Sir/Mam:

I'm expermenting in the loop and array but....

how do i make a for loop items/numbers to become an array items/numbers... i mean it's just like this...

 

<?php

echo "DISPLAY THE LOOP NUMBERS

";

 

$multiplier = 5;

 

for($number=1; $number<=10; $number++)

{

 

$answer = $number * $multiplier;

echo $answer. '

';

}

 

 

// I assign a variable to hold the array

$result = array($answer);

 

 

echo "

 

";

echo "DISPLAY THE ARRAY FROM LOOP

";

 

 

// I want to display the array

foreach ($result as $display_numbers)

{

echo $display_numbers;

}

 

 

?>

 

 

BUT IT JUST DISPLAY 50 in the end... not the numbers that I'm expecting like (5,10,15,20,25,30,35,40,45,50)

 

All replies are appreciated! Thanks a lot! :)

Edited by madmhan84
Link to comment
Share on other sites

Looks like you are getting confused... the $answer variable does change throughout the loop, but it = 50 when the loop completes, and you only create your array once the loop completes. You need to add values to your array inside the loop.

 

Here is working code:

 

$multiplier = 5;

// Create loop
for($number=1; $number{
   $answer = $number * $multiplier;
   $array[$number] = $answer;

   echo  $answer. '
';
}

echo "

";
echo "DISPLAY THE ARRAY FROM LOOP
";

// display array
foreach ($array as $display_numbers)
{
   echo $display_numbers.'
';
}

?>

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...