check if list of vars are empty, and if not, move to string in PHP

115 views Asked by At

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;
?>
2

There are 2 answers

3
shauns2007 On BEST ANSWER

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.

0
VishalParkash On

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;
?>