Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_push not working within function, PHP

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.

like image 578
devjs11 Avatar asked Nov 23 '13 23:11

devjs11


2 Answers

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.

like image 65
Ry- Avatar answered Oct 22 '22 07:10

Ry-


You need to pass the array by reference.

function online($thekey, &$mailarray) {
like image 29
kero Avatar answered Oct 22 '22 08:10

kero