1

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!

3
  • function f($ar=array(), &$gl=array()) --?? Commented Dec 24, 2017 at 12:04
  • what do you need to do? Commented Dec 24, 2017 at 12:06
  • I need to fill the $globals array with values from other arrays. Commented Dec 24, 2017 at 12:09

3 Answers 3

1

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

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

Comments

0

man first you should modify the function to return the value and assign the returned value for the value to be printed . you are print the $global and it is an empty array . 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 ) )
?>

1 Comment

No sir. But each function call will fill the array with a new value.
0

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); 

2 Comments

Thank You :) But each event new index of $globals is unknown.
$array_example is getting data in loop from MySQL

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.