so I am trying to modify an array by adding key and value in a function modArr
; I expect the var dump to show the added items but I get NULL. What step am I missing here?
<?php
$arr1 = array();
modArr($arr1);
$arr1['test'] = 'test';
var_dump($arr);
function modArr($arr) {
$arr['item1'] = "value1";
$arr['item2'] = "value2";
return;
}
The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).
Accessing Elements in a PHP Array The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]).
An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values. To create an array in PHP, we use the array function array( ) . By default, an array of any variable starts with the 0 index.
You are modifying the array as it exists in the function scope, not the global scope. You need to either return your modified array from the function, use the global
keyword (not recommended) or pass the array to the function by reference and not value.
// pass $arr by reference
$arr = array();
function modArr(&$arr) {
// do stuff
}
// use global keyword
$arr = array();
function modArr($arr) {
global $arr;
//...
}
// return array from function
$arr = array();
function modArr($arr) {
// do stuff to $arr
return $arr;
}
$arr = modArr($arr);
To learn more about variable scope, check the PHP docs on the subject.
you have to pass $arr
by reference: function modArr(&$arr)
edit: noticed an error in your code: you are passing modArr($arr1);
but trying to output $arr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With