user1170392
user1170392

Reputation:

amateur with arrays

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

Upvotes: 0

Views: 69

Answers (1)

Eineki
Eineki

Reputation: 14909

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

$pizza='1-4,2,3-1,5-4,7';
preg_match_all("/\d\-\d/", $pizza, $return);
var_dump($return);

Will have a similar, less confusing, result (there are not parens in the regex).

array
  0 => 
    array
      0 => string '1-4' (length=3)
      1 => string '3-1' (length=3)
      2 => string '5-4' (length=3)

If you find easier the print_r format:

Array ([0]=>Array([0]=>1-4 [1]=>3-1 [2]=>5-4))

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:

foreach ($return[0] as $slice) {
    <do whatever you need with $slice >
}

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:

$pizza='1-4,2,3-1,5-4,7';
$return = array_filter(
    explode(',',$pizza), // turn the string into an array
    function($x){return strpos($x,'-');} // filter out the slices without a -
);

foreach ($return as $slice) { // NOTE: no $return[0]
    <do whatever you need with $slice >
}

But this is just a matter of personal taste since the differences in performance are negligible with such a little data amount to manipulate.

Upvotes: 2

Related Questions