0


I am trying to push the output of a for loop into an array but I am not being able to do so. Following is the code that I have written:

<?php
$n = 14;
for ($i = 2; $i <= $n; $i++) 
{ 
    for ($j = 2; $j <= $n; $j++) 
    { 
        if ($i%$j == 0) // if remainder of $i divided by $j is equal to zero, break. 
        {
            break;
        }
    }
    if ($i == $j) // 
    {
        $form = $i;
        //echo $form;
        $numArray = array();
        array_push($numArray, $form); // Here I am trying to push the contents from the `$form` variable into the `$numArray`
        print_r($numArray);                 
    }
}
?>

The output that I obtain through this is:

Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 5 ) Array ( [0] => 7 ) Array ( [0] => 11 ) Array ( [0] => 13 )

Here, we see that the array index basically remains the same, so it has no scope for future use. So, how can I make this seem like as shown below:

Array ( [0] => 2 ) Array ( [1] => 3 ) Array ( [2] => 5 ) Array ( [3] => 7 ) Array ( [4] => 11 ) Array ( [5] => 13 )

Please note that, $n in the code can be any number less than 101 and greater than 1. Thank you for your precious time put into reading and trying to helping me out. :)

1 Answer 1

3

The $numArray should be declared once, not every time in the loop. And you can simply add value to the array by using expression like: $numArray[] = $i; Try this code:

<?php

$numArray = array();
$n = 14;
for ($i = 2; $i <= $n; $i++) {
    for ($j = 2; $j <= $n; $j++) {
        if ($i % $j == 0) { // if remainder of $i divided by $j is equal to zero, break. 
            break;
        }
    }
    if ($i == $j) {
        $numArray[] = $i;
    }
}
print_r($numArray);
Sign up to request clarification or add additional context in comments.

9 Comments

I am trying it out. Wait a second brother. :)
It worked. Btw, I tried to include the print_r($numArray) inside the for loop to watch out what happens next, and it output a weird result. :( . Loads of love, from India.
It will print array with elements 1 first time, 2 second time, 3 third time & so on.
I bet that is the exact reason why Lovepreet placed the print_r outside.
PHP automatically initialize it while assigning values inside the loop $numArray[] = $i; here. But it's safe to declare and initialize above, in case if condition not true even once.
|

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.