Home >Backend Development >PHP Tutorial >How Can I Let a PHP Function Access and Modify an External Array?

How Can I Let a PHP Function Access and Modify an External Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-12 20:29:16829browse

How Can I Let a PHP Function Access and Modify an External Array?

Granting Functions Access to External Variables

Your question revolves around providing a function with access to an external array, allowing it to modify and append values. By default, functions do not have direct access to variables defined outside their scope.

To grant access, you can utilize the global keyword within the function.

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

While this approach grants access, using global variables is generally discouraged as it compromises the function's independence. A more preferred technique is to return the modified array from the function.

function someFunction(){
    $myArr = array();       // At first, you have an empty array
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
    return $myArr;
}

$result = someFunction();

Alternatively, you can have your function accept the array as a parameter and modify it by reference.

function someFunction(array & $myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
}

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it

This approach maintains the function's independence while allowing it to operate on the external array. For further information, refer to the PHP manual sections on Function Arguments and Returning Values.

The above is the detailed content of How Can I Let a PHP Function Access and Modify an External Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn