I have a form where sometimes a field appears and other times it doesn't , and since the validation with PHP I need to store all the values of the fields in variables .
So I can't do this because I would get an error:
$nombre = $_POST['nombre'];
But I don't want to do this either because there are a lot of fields and I would like to do it in a more efficient way if possible:
if (isset($_POST)) {
$nombre = $_POST['nombre'];
}
Is there an alternative that for example leaves the variable with NULL (for example) if the field does not exist and in a more efficient way?
For these cases I use a ternary operator, verifying the POST with
empty
.Another possibility
If you want to avoid a lot of checks, another thing you can do is send an ordered object from the client, where inside the global object, you put a nested object with the required values.
Let's imagine a scenario where, in order for a certain action to be executed on the server, data for
nombre, apellido, direccion, edad
.Assuming that we are using Ajax, which would be the most common, you can pass an object to the server like this:
On the server, a simple check would be made, based on verifying if there is a key in the POST
required
or not:This is one possibility, if you want to avoid long type checks
if ($dato1 && $dato2 && dato99) {
in case there is a lot of required data. Emphasizing again that in the client there must be a strict control so that none of this data passes empty.Also if you are using PHP 7 or later you can use the NULL COALESCENCE OPERATOR like so
I quote
Operator Reference
A quick way is to use the error-handling operator, the at sign (@), which suppresses the error message that might be generated when searching for an undefined key.
The warnings are intended to guide the developer in correcting errors, and although the @ operator prevents the warning from being printed on the screen, the error still exists. Ignoring warnings is frowned upon as it means you know your code has bugs and you don't care to fix them.
When I have to mock up a webhook I use this technique: