0

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:

  • Check posted $vars 1 to 10 to see if they contain a value.
  • For each one that has no value, remove it from the string. Where a value is present, add it to the string.

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;
?>
Praveen
  • 6,872
  • 3
  • 43
  • 62
  • I wonder if your logic is backwards, as you are not checking the values of *$vars 1 to 10*, but of `$Lot_no` and `$Flat_unit_no`. I would assume you are wanting to check `if (empty($v1))`. And then your `$str` would actually be `$str= $Lot_no . $Flat_unit_no;` – Sean Dec 20 '16 at 05:45
  • hi, can you output values for $vars – YaHui Jiang Dec 20 '16 at 05:48

2 Answers2

0

Try this one. You can check the value if it is equals to 0 or not.

<?php
    if((empty($Lot_no)) && ($Lot_no =='0')){ 
        $Lot_no = $v1;
    }if ((empty($Flat_unit_no)) && ($Lot_no =='0')){
        $Flat_unit_no  = $v2;
    }
    $str= $v1. $v2;
?>
VishalParkash
  • 490
  • 3
  • 15
0

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.

Community
  • 1
  • 1
shauns2007
  • 128
  • 9