Address String Issue

Discussion in 'PHP' started by Omzy, Dec 30, 2008.

  1. #1
    Here is my current address string:

    $address=$address1.", ".$address2.", ".$district.", ".$town.", ".$county.", ".$postcode;
    Code (markup):
    The problem is sometimes a client does not provide an 'address2' or 'district', in some cases both are not provided in which case the address string has unnecessary comma's in.

    How can I get around this problem?
     
    Omzy, Dec 30, 2008 IP
  2. tonybogs

    tonybogs Peon

    Messages:
    462
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try something simple like:

    $address2 = !empty($address2) ? $address2.", " : "";
    $district = !empty($district) ? $district.", " : "";

    This will append a comma to the $address2/$district variable only if it is not empty. Then in your concat string you can try...

    $address=$address1.", ".$address2.$district.$town.", ".$county.", ".$postcode;

    Hope this helps :)
     
    tonybogs, Dec 30, 2008 IP
  3. bigpapa

    bigpapa Banned

    Messages:
    273
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    bigpapa, Dec 30, 2008 IP
  4. Omzy

    Omzy Peon

    Messages:
    249
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    tonybogs - Seems like a good solution but I'm thinking there must be a more 'elegant' way of doing this?

    bigpapa - I've worked with arrays before but how would I use an array in this scenario?
     
    Omzy, Dec 31, 2008 IP
  5. nabil_kadimi

    nabil_kadimi Well-Known Member

    Messages:
    1,065
    Likes Received:
    69
    Best Answers:
    0
    Trophy Points:
    195
    #5
    
    //testing variables:
    $address1 = "1 Bd Zerktouni";
    $town = "Casablanca";
    $country = "Morocco";
    
    //My suggestion f
    $address = '';
    $address_parts = array('address1', 'address2', 'district', 'town', 'country', 'postcode');
    foreach($address_parts as $address_part){
      if(isset($$address_part) && trim($$address_part))
        $address.= $$address_part.', ';
    }
    $address = substr($address, 0, -2); // removes the last ', '
    
    echo $address;
    
    //Output:  1 Bd Zerktouni, Casablanca, Morocco
    
    
    PHP:
     
    nabil_kadimi, Dec 31, 2008 IP