11

I have array_push() inside of a function and need to run it inside a foreach() filling the new array. Unfortunately I can't see why this does not work.

$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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

9

You need to pass the array by reference.

function online($thekey, &$mailarray) {

Comments

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.