8

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

2 Answers 2

18

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.

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

Comments

3

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

1 Comment

For PHP 5.4+, & had removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.