Why does this not work to assign a default value to a function variable?

I have the following simple script. Function acAction looks for a passed var $acAction, and if not present the default value for $acAction should be “account/view”. But when I echo $acAction it is null. Why doesn’t $acAction get assigned the default value?

<?php
// Define the function
function acAction( $acAction = "account/view", $acArray) {
	echo "Is " . $acAction;
}
?>

<?php
// Call the function
$acActionResult = acAction($acAction, $acArray);
?>

The default must be the right side parameter.

Per the manual:
https://www.php.net/manual/en/functions.arguments.php

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

<?php
// Define the function
function acAction($acArray, $acAction = "account/view") {
    echo "Is " . $acAction;
}

$acArray = '';
acAction($acArray);
1 Like

Alternatively you could give both parameters a default:

function acAction($acAction = "account/view", $acArray = []) {
	echo "Is " . $acAction;
}
?

Also, what is ac? I’d recommend using meaningful variable names. You probably know what it means now, but what about next month? Next year? In a few years?

Also in your example you override the default value.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.