Search code examples
phpfatal-error

Understanding Fatal error: Cannot use temporary expression in write context


I would like to understand exactly what this error means in PHP: how the error can be created on purpose and how to avoid or fix it. In my simple example below, I got this error:

Fatal error: Cannot use temporary expression in write context in line 11

Line 11 is the following line:

response['error'] = "Error: B is less that C <br />";

Here is the erroneous code:

$response = [];
$a = 4;
$b = 8;
$c = 9;
$d = 29;

if($a !== $b){
    $response['error'] = "Error: A is not equal to B <br />";
}elseif($b < $c){
    response['error'] = "Error: B is less that C <br />";
}
if($d > $c){
    response['success'] = "Success: D is greater than C<br />";
}

echo $response['error'];
echo $response['success'];

My expectation is:

Making sure this exception is correctly handled

I know the variables are defined, otherwise the error would be:

Notice: Undefined variable


Solution

  • You have forgotten to include the $ before the word response.

    This is apparent in lines 11 and 14 like so:

    response['error'] = "Error: B is less that C <br />";
    

    You should change it to:

    $response['error'] = "Error: B is less that C <br />";
    

    Hope this helps.