-4

I need to change some words to numbers. Example is below-

$status= str_replace(array("canceled","shipped","processing","complete","pending_payment","closed","fraud","holded","payment_review","pending"),array(4,6,2,10,1,12,0,1,1,2),$sale["status"]);

But if unexpected words come from DB ı want to change it to 0.

Is this possible?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Ismail
  • 17
  • 1
  • 10
  • 3
    it is possible, what have you tried? – omxv Feb 22 '17 at 12:56
  • Use a simple switch statement, much easier to read and maintain and offers a `default` directive. – arkascha Feb 22 '17 at 12:57
  • Actually i used it if conditions something like this;elseif status1="pending" then status=2 else status=0 end if But I dont know how i can do this with str_replace – Ismail Feb 22 '17 at 12:57
  • Maybe `if (!in_array($sale["status"], array(4,6,2,10,1,12,0,1,1,2)) { $sale["status"] = 0 } else { str_replace stuff}`? ... or you could just ternary the assignment... or you could do this in DB with a `case` and `in`. – chris85 Feb 22 '17 at 12:58
  • use `preg_replace()` :-https://eval.in/741019 – Alive to die - Anant Feb 22 '17 at 13:01

2 Answers2

1

You could do something like this :

   $statuses = [
      "canceled" => 4,
      "shipped" => 6,
      "processing" => 2,
      "complete" => 10, 
      "pending_payment" => 1,
      "closed" => 12,
      "fraud" => 0,
      "holded" => 1,
      "payment_review" => 1,
      "pending" => 2,
    ];

    $status = 0;

    if (isset($statuses[$sale["status"]])) { 
        $status = $statuses[$sale["status"]];
    }

This way you can easily see which string value maps to which number. Set the default for $status variable to 0. If the status string given, exists in your "statusmap", replace the $status variable.

axelvnk
  • 442
  • 1
  • 6
  • 15
0

Try this,

$status_words = array("canceled", "shipped", "processing", "complete", "pending_payment", "closed", "fraud", "holded", "payment_review", "pending");
$status_ints = array(4, 6, 2, 10, 1, 12, 0, 1, 1, 2);
$status = (in_array(trim($sale["status"]), $status_words) ? 
           str_replace($status_words, $status_ints, trim($sale["status"])) : '');

Give it a try, this should work.

Rahul
  • 18,271
  • 7
  • 41
  • 60