Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: cannot modify array in function?

Tags:

php

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;
}
like image 390
KJW Avatar asked Dec 08 '11 06:12

KJW


People also ask

What is array_ shift in PHP?

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

How to access an element in an array PHP?

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 ([]).

How array work in PHP?

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.


2 Answers

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.

like image 89
rdlowrey Avatar answered Oct 07 '22 12:10

rdlowrey


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

like image 45
k102 Avatar answered Oct 07 '22 11:10

k102