user3006927 user3006927 - 15 days ago 9
PHP Question

How can I create a function that pushes elements into an array?

Trying to figure out why this function isn't pushing anything to the array I defined. When I print_r $location_matches it is empty.

$id = get_the_ID();
$location_matches = array();

function find_location_meta($location_id, $product_id, $location_matches_arr) {
$meta_info = get_post_meta($location_id);
$working_with = unserialize($meta_info[locations_products_carried][0]);
for ($i = 0; $i < count($working_with); $i++) {
if ( $working_with[$i][locations_products][0] == $product_id ) {
array_push($location_matches_arr, $working_with[$i]);
}
}
}

find_location_meta(94, $id, $location_matches);

Answer

You need to make a passage by reference if you would like to change a variable that way so :

$id = get_the_ID();
$location_matches = array();

function find_location_meta($location_id, $product_id, &$location_matches_arr) {
    $meta_info = get_post_meta($location_id);
    $working_with = unserialize($meta_info[locations_products_carried][0]);
    for ($i = 0; $i < count($working_with); $i++) {
        if ( $working_with[$i][locations_products][0] == $product_id ) {
            array_push($location_matches_arr, $working_with[$i]);
        }
    }
}

find_location_meta(94, $id, $location_matches);

You would notice that I added & in the declaration of the function so it could point to that exact variable and change it's content.