i want some hints for php
Here is my variables like this
$error;
$a=$_POST["sdf"];
$b=$_POST["dsf"];
$c=$_POST["ssdfsdfdf"];
$d=$_POST["ssdfsddf"];
$e=$_POST["sdfsdfdf"];
$f=$_POST["sfsdfsdf"];
$g=$_POST["sdsdff"];
$g=$_POST["sdsdfsdff"];
I want to check whether those variables are empty or not and dispaly message like this
if(empty($a)){
$error.="Hey you missed the $a "; // $a value
}
now i have to repeat all those codes ...
Imagine i have more than 40 variables can i get some hints to short that code
i tried switch statement but it's not working ..i want to display all error message of anyone variable is missing...
Regards
$required = ["sdf", "dsf", "ssdfsdfdf"]; //etc. etc.
$arr = [];
//Loop through and santize input.
foreach($_POST as $key => $value)
{
//sanitize input here
//store in array
$arr[$key] = $value;
}
//check empty
foreach($arr as $key => $value)
{
if(in_array($key, $required)
{
if(empty($value))
{
throw new Exception("One of the required attributes is empty");
}
}
}
Don't assign to a variable. You can process the POST array directly
foreach($_POST as $value) {
if(is_array($value)) {
foreach($value as $val) {
if(empty($val)){
$error.="Hey you missed the $val "; // $a value
}
}
} else {
if(empty($value)){
$error.="Hey you missed the $value "; // $a value
}
}
}
If you want to check all POST
variables in the page try using foreach like this
foreach($_POST as $key=>$values)
{
if($values == "")
echo "Hey you missed out ".$key;
}
Note
: Use sensible naming in key(POST variables) so that it helps in displaying message