PaulB3434 PaulB3434 - 6 months ago 12
PHP Question

PHP - Splitting string lines up into two variables

Not sure how I would do this but if someone could point me in the right track that'll be great, basically I've got a lone line of text in a variable which looks like this:

Lambo 1; Trabant 2; Car 3;


Then I want to split "Lambo" to it's own variable then "1" to it's own variable, and repeat for the others. How would I go and do this?
I know about explode() but not sure how I would do it to split the variable up twice etc.

As requested in the comments my desired output would be like this:
$Item = "Lambo"
$Quantity = 1
Then echo them out and go back to top of loop for example and do the same for the Trabant and Car

Answer
<?php
$in = "Lambo 1; Trabant 2; Car 3;";
foreach (explode(";", $in) as $element) {
        $element = trim($element);
        if (strpos($element, " ") !== false ) {
                list($car, $number) = explode(" ", $element);
                echo "car: $car, number: $number";
        }
}

You can use explode to split the input on each ;, loop over the results and then split over each .