It is deemed as valid because it is not a syntax error. When you do this:
if ($page['title'] = 'current_page')
the =
which is the assignment operator tells PHP to assign the value current_page
to the array variagle $page['title']
, irrespective of whatever that variable contained earlier. Effectively, the $page['title']
variable now contains the value current_page
. Now, a successful assignment operation evaluates to the boolean value TRUE
, which makes the entire if
condition true.
What you have is a logic error. It is not caught by the interpreter/compiler. Rather such errors cause (serious) issues at runtime (as what you experienced) if left undetected.
One way some people advocate to avoid such errors is to invert the order of your operands thus:
if('current_page' = $page['title'])
In this case, PHP sees that you are trying to assing a variable to a literal, which is an invalid operation, and reports an error, which is caught at compile time. The error forces you to look clearly at your code, and to fix it by using the comparison operator ==
if('current_page' == $page['title'])
Bottom line: The =
is the ASSIGNMENT operator, while the ==
is the COMPARISON operator. Being aware of the distinction between ASSIGNMENT and COMPARISON will help you write better code.