1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

replace value in array if a field is empty

Discussion in 'PHP' started by Silvester Vella, Jun 30, 2016.

  1. #1
    I am new with php so this might be a silly question. I have this code..

    $message = str_replace( array( '%TITLE%', '%VOUCHER%', '%BUYERUSER%', '%DEALPRICE%', '%DIFFERENCE%', '%DATEOFPURCH%' ), array( $offer->post_title, $voucher_code, $user->user_nicename, $offer->deal_owner_price, $offer->deal_sale_price - $offer->deal_owner_price, date("d/m/y") ), $message ); 
    Code (markup):
    now I would like to set the value of '%DIFFERENCE%' to a string saying not available or something, if $offer->deal_sale_price field is left empty. Any help please?

    Thanks.
     
    Last edited by a moderator: Jun 30, 2016
    Silvester Vella, Jun 30, 2016 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Easiest way would be to check the value before using it. Something like this (before the str_replace, just swap the $offer->deal_sale_price with $offer_price in the array) :
    $offer_price = (empty($offer->deal_sale_price) ? 'not available' : $offer->deal_sale_price);
     
    PoPSiCLe, Jun 30, 2016 IP
  3. Silvester Vella

    Silvester Vella Greenhorn

    Messages:
    22
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    Really sorry but I didnt quite get how the end code should be. I am completely new in php so please bear with me :)
     
    Silvester Vella, Jun 30, 2016 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    
    $offer_price = (empty($offer->deal_sale_price) ? 'not available' : $offer->deal_sale_price - $offer->deal_owner_price);
    
    $message = str_replace( array( '%TITLE%', '%VOUCHER%', '%BUYERUSER%', '%DEALPRICE%', '%DIFFERENCE%', '%DATEOFPURCH%' ), array( $offer->post_title, $voucher_code, $user->user_nicename, $offer->deal_owner_price, $offer_price, date("d/m/y") ), $message ); 
    PHP:
    That should do it.
     
    PoPSiCLe, Jun 30, 2016 IP
  5. Silvester Vella

    Silvester Vella Greenhorn

    Messages:
    22
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #5
    worked beautifully mate. Thanks a lot :)
     
    Silvester Vella, Jul 5, 2016 IP