I'm trying to declare variables and arrays from a form (post) but it seems the arrays are not being processed:
// is this a better practise than directly pass the entire $_POST?
$list = array('use', 'type', 'status', 'bhk', 'baths', 'size', 'location', 'price', 'description');
foreach($list as $name) {
if ($name != 'description')
$var = "\$" . $name . "=filter_input(INPUT_POST, '" . $name . "', FILTER_SANITIZE_NUMBER_INT);";
else if ($name == 'description')
$var = "\$" . $name . "=filter_input(INPUT_POST, '" . $name . "', FILTER_SANITIZE_STRING);";
}
$area_1 = $size['area1'] != '' ? $size['area1'] : 0;
$area_2 = $size['area2'] != '' ? $size['area2'] : 0;
$city = $location['city'];
$zone = $location['zone'];
$sale = $price['sale'] != '' ? $price['sale'] : 0;
$rent = $price['rent'] != '' ? $price['rent'] : 0;
Could be that some of those inputs are long numbers? Like $price['sale']
(up to 999999) or $size['area1']
(up to 999). Since they don't need any unit type I prefer storing them as integers rather than strings. But tell me if the length is a problem.
EDIT: (FIX by @swidmann in comments)
$$name = filter_input(INPUT_POST, $name, FILTER_SANITIZE_NUMBER_INT);
Solution: (by @swidmann in comments)
$$name = filter_input(INPUT_POST, $name, FILTER_DEFAULT , FILTER_REQUIRE_ARRAY)
To create variables from your array you should use $$
instead of concatenating a string an run eval()
, because eval() is evil.
You can make variables like this:
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT );
with $$name
you can define a variable with the name of the string content $nam
e
If your input can be an array, please take a look at filter_input_array() or filter_input() with the option FILTER_REQUIRE_ARRAY
, depends on what you need.
Here is an approach:
// is this a better practise than directly pass the entire $_POST?
$list = array( 'use', 'type', 'status', 'bhk', 'baths', 'size', 'location', 'price', 'description' );
foreach ( $list as $name ) {
if ( $name != 'description' ) {
if( is_array( $_POST[$name] ) ) {
// I think you should also check for other types if needed (i.e. string)
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT , FILTER_REQUIRE_ARRAY );
} else {
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT );
}
} else if ( $name == 'description' ) {
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_STRING );
}
}
$area_1 = $size['area1'] != '' ? $size['area1'] : 0;
$area_2 = $size['area2'] != '' ? $size['area2'] : 0;
$city = $location['city'];
$zone = $location['zone'];
$sale = $price['sale'] != '' ? $price['sale'] : 0;
$rent = $price['rent'] != '' ? $price['rent'] : 0;
if you are not sure about the input, you can try the option FILTER_DEFAULT:
$$name = filter_input(INPUT_POST, $name, FILTER_DEFAULT , FILTER_REQUIRE_ARRAY)