Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of methods appending arrays in a foreach loop

I've set up an array of associative arrays (with dummy data for testing) like this:

// To hold dropdown filter options
$results['filters'] = array('Client' => array( array('a' => '1') ),
                            'Project' => array( array('b' => '2') ), 
                            'Status' => array( array('c' => '3') ), 
                            'User' => array( array('d' => '4') )
                           );

Can anyone tell me why this works:

// Add 'All' option to the top of each filter dropdown 
foreach($results['filters'] as $filter_key => $filter_value) {
    $results['filters'][$filter_key][] = array('name' => 'All');
}

But this doesn't:

// Add 'All' option to the top of each filter dropdown 
foreach($results['filters'] as $filter_key => $filter_value) {
    $filter_value[] = array('name' => 'All');
}

When I do print_r($results) inside the the loop it appears to be working (appending the row to existing data), but checking it outside of the loop makes it seem like the loop has has no effect on the arrays.

Thanks

like image 413
Vilāsamuni Avatar asked Dec 07 '25 13:12

Vilāsamuni


1 Answers

You need to pass the $filter_value as reference (with a leading &) instead of a copy.

foreach($results['filters'] as $filter_key => &$filter_value) {
    $filter_value[] = array('name' => 'All');
}

Documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

like image 114
Rayne Avatar answered Dec 09 '25 06:12

Rayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!