Checking variables in PHP

red pen writing a red tickChecking variables in PHP can be achieved in three ways.

The first is to use the isset function which checks if the variable has been set. Generally this really shouldn't be needed much as a programmer should always have all their variables set. But it is needed when forms are used on a website. One particular circumstance is a checkbox. If a checkbox has not been checked then a value is not sent through to the server. Therefore we have to check if it exists.

<?php if (isset($_POST['check-me'])) { /* checkbox has been checked */ } ?> <input type="checkbox" name="check-me" value="checked" />

The second way that we check for a PHP variable is to see if the variable contains a certain value. This is done with two equal signs.

<?php $variable = 'abc'; if ($variable == 'abc') { /* yes variable is equal to abc */ }

There is also a special third way to check a PHP variable and that is with 3 equal signs. We are now asking if a variable is equal to and of the same type. For example

<?php $variable = '1'; /* this is a string as there are apostrophes around the number */ if ($variable == 1) { /* true */ /* this is true as the string 1 is equal to an integer 1 */ } if ($variable === 1) { /* false */ /* this is false as $variable is a string 1 and we check for integer 1 */ }

Now that we know the ways of checking PHP variables, we can combine them whilst using forms. The format is to first check if the variable exists and then check if it is equal to what we are looking for. You should remember that all form values are sent to the server as strings, therefore we never use 3 equal signs.

<?php /* check that the hidden input task has been sent through, /* and check that the value is equal to save if (isset($_POST['task']) && $_POST['task'] == 'save') { /* incorrect as form values are sent through as strings and will never be an integer */ if ($_POST['number'] === 5) {} /* correct */ if ($_POST['number'] == 5) {} } ?> <form method="post"> <input type="hidden" name="task" value="save" /> <label for="name">Number</label> <input type="input" id="number" name="number" /> </form>