d3bug3r
d3bug3r

Reputation: 2586

Php array explode a char

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

Upvotes: 1

Views: 39

Answers (2)

Chris Trudeau
Chris Trudeau

Reputation: 1437

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

Upvotes: 1

Barmar
Barmar

Reputation: 781751

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);

Upvotes: 1

Related Questions