array_push not working within function, PHP
Asked Answered
D

2

11

I have this case when I have array_push inside function and then I need to run it inside foreach filling the new array. Unfortunately I can't see why this does not work. Here is the code:

<?php

$mylist = array('house', 'apple', 'key', 'car');
$mailarray = array();

foreach ($mylist as $key) {
    online($key, $mailarray);
}

function online($thekey, $mailarray) {

    array_push($mailarray,$thekey);

}

print_r($mailarray);

?>

This is a sample function, it has more functionality and that´s why I need to maintain the idea.

Thank you.

Deyo answered 23/11, 2013 at 23:42 Comment(0)
B
19

PHP treats arrays as a sort of “value type” by default (copy on write). You can pass it by reference:

function online($thekey, &$mailarray) {
    $mailarray[] = $thekey;
}

See also the signature of array_push.

Boiler answered 23/11, 2013 at 23:44 Comment(2)
Thank you so much! I think I would never be able to resolve that.Deyo
Over 10 years later, this answer saved my bacon!Mezuzah
X
9

You need to pass the array by reference.

function online($thekey, &$mailarray) {
Xiaoximena answered 23/11, 2013 at 23:44 Comment(1)
Thank you so much. I find it hard to accept the answer as you both posted at the same time! I just want to say thank you very much!!! @minitechDeyo

© 2022 - 2024 — McMap. All rights reserved.