Frash
Frash

Reputation: 67

How to add strings to an array inside a php function

I have this function that doesn't work.
$b is an outside string that should bond with $a array that should return a group of strings.

$a=array('this','is');
function chkEdt($a,$b) {
 $a[]=$b;
};
print_r($a);

Result -> array();

Why?

Upvotes: 0

Views: 354

Answers (2)

ADyson
ADyson

Reputation: 61914

Your example never actually calls the chkEdt function, and that function never returns anything.

Aside from that, variables have different scope inside and outside functions - even though they share a name, they are considered to be different variables because one of them is inside a function. Read https://php.net/manual/en/language.variables.scope.php for more detail.

You can either pass the variable by reference as in Barmar's answer, or you can make the function return a value and then re-assign the $a outside the function to the value returned by the function - like this:

$a = array('this','is');

function chkEdt($a,$b) {
 $a[] = $b;
 return $a;
};

$a = chkEdt($a, "a");
print_r($a);

Live demo: http://sandbox.onlinephpfunctions.com/code/00d19028b3909ca415b81e93c26a6ede9188c743

To clarify the difference, you could re-write the function with a different variable name within the function, and get the same result:

$a = array('this','is');

function chkEdt($z,$b) {
 $z[] = $b;
 return $z;
};

$a = chkEdt($a, "a");
print_r($a);

Upvotes: 0

Barmar
Barmar

Reputation: 781096

You need to make it a reference parameter.

function chkEdt(&$a,$b) {
    $a[]=$b;
};

Then any changes to $a in the function will affect the array variable that's used as the argument.

Upvotes: 2

Related Questions