Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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

function online($thekey, &$mailarray) {
    array_push($mailarray, $thekey);
}

See also the signature of array_push.

Scroll down a bit from here.

share|improve this answer
    
Thank you so much! I think I would never be able to resolve that. –  devjs11 Nov 24 '13 at 0:02

You need to pass the array by reference.

function online($thekey, &$mailarray) {
share|improve this answer
    
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!!! @minitech –  devjs11 Nov 24 '13 at 0:01
    
You are welcome. Feel free to accept either one, no hurt feelings –  kingkero Nov 24 '13 at 0:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.