So lets say I have an string like so.
$pizza = 1,2,3,5-4,7;
and what I want to get out of it is the 5-7 out of that set but that 5-7 could be any combo, say 6-9 or 10-1 and this occur multiple times.
Such as
$pizza=1-4,2,3-1,5-4,7;
Then I got help to use
preg_match_all("/(\d\-\d)/", $pizza, $return);
Which gives me this
print_r($return);
Array ( [0] => Array ( [0] => 5-7 ) [1] => Array ( [0] => 5-7 ) )
So how do I get that value (5-7) and assign it to a variable like $slice
You should already know the synopsis of preg_match_all.
The third parameter is an array that contains all the matches found in your text (second parameter).
It is a array containing a set of different array: The first one contains al the pattern matched. The others are the matches of subpatterns. I’m not here to write an essay on regular expression then I will assume that you know them (a refresh: subpatterns are those things enclosed by parentheses and, in your case, are quite useless).
Will have a similar, less confusing, result (there are not parens in the regex).
If you find easier the print_r format:
To consume an array one element at a time you can use the foreach control structure.
The code to do your exercise should be similar to this:
The code in the braces will run as many times as elements into the array $return[0] (the array with the matched slices) and $slice will assume the value of the different elements
in the different runs.
Hope this solves your doubts.
Said that I would have used a different approach to solve your task:
But this is just a matter of personal taste since the differences in performance are negligible with such a little data amount to manipulate.