[php] Giving my function access to outside variable

I have an array outside:

$myArr = array();

I would like to give my function access to the array outside it so it can add values to it

function someFuntion(){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

How do I give the function the right scoping to the variable?

This question is related to php function scope

The answer is


$myArr = array();

function someFuntion(array $myArr) {
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;

    return $myArr;
}

$myArr = someFunction($myArr);

The one and probably not so good way of achieving your goal would using global variables.

You could achieve that by adding global $myArr; to the beginning of your function. However note that using global variables is in most cases a bad idea and probably avoidable.

The much better way would be passing your array as an argument to your function:

function someFuntion($arr){
    $myVal = //some processing here to determine value of $myVal
    $arr[] = $myVal;
    return $arr;
}

$myArr = someFunction($myArr);

$foo = 42;
$bar = function($x = 0) use ($foo){
    return $x + $foo;
};
var_dump($bar(10)); // int(52)

UPDATE: there is now support for arrow functions, but i will let for someone that used it more to create the answer


Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

Be forewarned, generally people stick away from globals as it has some downsides.

You could try this

function someFuntion($myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
    return $myArr;
}
$myArr = someFunction($myArr);

That would make it so you aren't relying on Globals.


Two Answers

1. Answer to the asked question.

2. A simple change equals a better way!

Answer 1 - Pass the Vars Array to the __construct() in a class, you could also leave the construct empty and pass the Arrays through your functions instead.

<?php

// Create an Array with all needed Sub Arrays Example: 
// Example Sub Array 1
$content_arrays["modals"]= array();
// Example Sub Array 2
$content_arrays["js_custom"] = array();

// Create a Class
class Array_Pushing_Example_1 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Primary Contents Array as Parameter in __construct
    public function __construct($content_arrays){

        // Declare it
        $this->content_arrays = $content_arrays;

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class with the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_1($content_arrays);

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Answer 2 - A simple change however would put it inline with modern standards. Just declare your Arrays in the Class.

<?php

// Create a Class
class Array_Pushing_Example_2 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Declare Contents Array and Sub Arrays in __construct
    public function __construct(){

        // Declare them
        $this->content_arrays["modals"] = array();
        $this->content_arrays["js_custom"] = array();

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class without the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_2();

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Both options output the same information and allow a function to push and retrieve information from an Array and sub Arrays to any place in the code(Given that the data has been pushed first). The second option gives more control over how the data is used and protected. They can be used as is just modify to your needs but if they were used to extend a Controller they could share their values among any of the Classes the Controller is using. Neither method requires the use of a Global(s).

Output:

Array Custom Content Results

Modals - Count: 5

a

b

c

FOO

foo

JS Custom - Count: 9

1

2B or not 2B

3

42

5

car

house

bike

glass


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to scope

Angular 2 - Using 'this' inside setTimeout Why Is `Export Default Const` invalid? How do I access previous promise results in a .then() chain? Problems with local variable scope. How to solve it? Why is it OK to return a 'vector' from a function? Uncaught TypeError: Cannot read property 'length' of undefined Setting dynamic scope variables in AngularJs - scope.<some_string> How to remove elements/nodes from angular.js array Limiting number of displayed results when using ngRepeat A variable modified inside a while loop is not remembered