0

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?

1
  • If you want the function to change the value of a parameter that's been passed to it, you need to pass by reference. Commented Sep 1, 2021 at 15:42

2 Answers 2

2

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.

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

1 Comment

Thank you Barmar, I'll study reference parameters.
0

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

Comments

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.