Forum Moderators: coopster

Message Too Old, No Replies

Arrays

... can values be pushed in during loop?

         

panic

11:42 pm on Sep 8, 2004 (gmt 0)

10+ Year Member



Is it possible to push values into an array while it's in a loop?

For example :

$array = array("1","2","3");

foreach($array as $int){
(stuff happens here)
}

Is it possible to push values into $array while in the loop?

coopster

12:00 am on Sep 9, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Yes.
<?php 
$array = array("1","2","3");
foreach($array as $int){
// array_push($array, 'push');
$array[]='push';
}
print '<pre>';
print_r($array);
pre '</pre>';
?>
Prints
Array 
(
[0] => 1
[1] => 2
[2] => 3
[3] => push
[4] => push
[5] => push
)
Note that foreach operates on a copy of the specified array and not the array itself.

panic

12:24 am on Sep 9, 2004 (gmt 0)

10+ Year Member



In that case, wouldn't it be best to push everything into another array, and output that when need be?

coopster

12:34 am on Sep 9, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Depends on what you are trying to accomplish. I just answered your question and showed you an example :)

panic

12:41 am on Sep 9, 2004 (gmt 0)

10+ Year Member



Thanks :)

Zipper

5:11 am on Sep 9, 2004 (gmt 0)

10+ Year Member




$array = array("1","2","3");
$count = = count($array);
for($i = 0; $i < $count; $i++){
$array[$count+$i] = "whatever";
}