I have read many things around the use of isset()
and empty
, but am not able to find the answer I am looking for.
Basically this: A user fills in some html inputs on post, which calls a php script. Prior to calling a separate web service to look up an address, I need to create a string with all of the address elements that have been populated. Where an input field has not been populated I want to exclude it from the list.
In short:
$vars
1 to 10 to see if they contain a value.I have tried using empty
, !empty
, isset
and still haven't worked it out.
Sample code:
<?php
if
(empty($Lot_no))
{ $Lot_no = $v1;
}
if (empty($Flat_unit_no))
{$Flat_unit_no = $v2;
}
$str= $v1. $v2;
?>
Do something like
$address = '';
foreach ($_POST as $post) {
if (!empty($post)) {
$address .= $post . ', ';
}
}
Here is another similar question that is similar. Why check both isset() and !empty()
If you want to add it to an array do something like this (I'm not sure on your form input names but as an example with form input names of street, city, state
$address = [];
$addressKeys = ['street', 'city', 'state'];
foreach ($_POST as $key => $post) {
if (in_array($key, $addressKeys)) {
$address[$key] = $post;
}
}
I didn't test this but it looks fine.