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

5
  • 3
    it is possible, what have you tried? Commented Feb 22, 2017 at 12:56
  • Use a simple switch statement, much easier to read and maintain and offers a default directive. Commented Feb 22, 2017 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 Commented Feb 22, 2017 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. Commented Feb 22, 2017 at 12:58
  • use preg_replace() :-eval.in/741019 Commented Feb 22, 2017 at 13:01

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.