php push to array from function

231

Nice day for all!

I need to fill the "global" array with other arrays. As an example, I wrote this function:

<?php
function f($ar=array(), $gl=array()){
    $gl[0]=array($ar[1]);
}
$globals=array();
$array_example=array('foo', 'bar');
f($array_example, $globals);
print_r($globals); //$globals is empty!
?>

Help me please. I can not understand why the var $globals is empty.

Thanks!

532

Answer

Solution:

I think you should pass the array by reference using&:

function f($ar = array(), &$gl = array())
{
    $gl[0] = array($ar[1]);
}

$globals = array();
$array_example = array('foo', 'bar');
f($array_example, $globals);
print_r($globals);

Will give you:

Array
(
    [0] => Array
        (
            [0] => bar
        )

)

Demo

70

Answer

Solution:

man first you should modify thefunction to return the value and assign the returned value for the value to be printed . you are print the$global and it is an emptyarray . so your code should be like this .

<?php
    function f($ar = array(), $gl = array()){
        $gl[0] = array($ar[1]);
        return $gl;
    }
    $globals=array();
    $array_example=array('foo', 'bar');

    $globals = f($array_example, $globals);
    print_r($globals); 

    // prints out Array ( [0] => Array ( [0] => bar ) )
?>
568

Answer

Solution:

Function always works on locally variables, And you want to use their locally variable scope to out of function. Check with below code, I hope it will help you

function f($ar=array(), $gl=array()){
    return array($ar[1]);
}
$globals=array();
$array_example=array('foo', 'bar');
$tmpArray = f($array_example, $globals);
$globals[0]=$tmpArray;
print_r($globals); 

People are also looking for solutions to the problem: php - Hide product attributes from additional information tab in WooCommerce

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.