I am getting a random number from user input (lets say $n
). Is it possible to create numeric array keys array(1, 2, 3, ....., $n )
up to the number given by the user? Actually I want to use it in a foreach loop and echo the value.
Here is one of the codes I have used.
$n = $_GET['num'];
foreach ($n as $a) {
echo $a;
}
How do I do that? Thanks in advance.
In foreach
a temporary memory of variable is created which gets flush after the loop has completed it's execution. Prefer to use foreach
when you already know that key | value
relationship exist.
To create an array upto $n, you can use a for
loop:
$array_up_to_n = array();
for ($i=1; $i<=$n; $i++)
{
$array_up_to_n[] = $i;
}
//you can verify it by:
print_r($array_up_to_n);
I hope you want this result and I have understood correctly
For Your Information:
whenever you use foreach
and you want to get result in an array, always declare an array before foreach
and use it inside like:
$my_array = array();
foreach ($result as $row)
{
$my_array[] = $row;
}
because $row
memory gets flushed after this loop
If you don't mind destroying $n
in the process, you can just decrement it:
for(;$n;$a[$n--]=1) {}
This creates the keys in reverse numeric order of course. You can always ksort()
if that's important.
Destroying $n
may not be much of an issue, because the same value should result from count($a)
after the for loop finishes.