1

This is my array:

array:4 [
  0 => "Family Deluxe for 4 Person x 1"
  1 => "Studio Deluxe for 2 Person x 1"
  2 => "Additional Adult x 2"
  3 => "Additional Children x 2"
]

When I pass into a foreach loop to remove the x and get the count, I encounter the following output result:

array:4 [
  0 => array:1 [
    "Family Delu" => "e for 4 Person "
  ]
  1 => array:1 [
    "Studio Delu" => "e for 2 Person "
  ]
  2 => array:1 [
    " Additional Adult " => " 2"
  ]
  3 => array:1 [
    " Additional Children" => " 2"
  ]
]

The issues is, there is x char in the string Deluxe so the loop getting confuse on where to start an explode(). Following were my code for foreach:

foreach($a as $s) {
            list($size, $quantity) = explode('x', $s);
            $data[] = array($size => $quantity);
            $sumVariant += $quantity;
        }

How can I get explode() to recognize the x with spaces on both side? Thanks!!

1
  • 1
    Put spaces around it: explode(' x ', $s) Commented Nov 24, 2015 at 1:39

2 Answers 2

1

The delimiter argument to explode() doesn't have to be a single character, it can be any string. So use x with spaces around it as the delimiter.

list($size, $quantity) = explode(' x ', $s);
Sign up to request clarification or add additional context in comments.

Comments

1

explode(" x ", $s); should do the trick. Or you could get the last item of the explode array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.