0

How can I use the PHP function explode() on each array entry?

For example:

foreach ($persons as $person) {
    $zips = $person->getZipResponsibility();
    $zips = nl2br($zips);

    $rangesArray = explode('<br />', $zips);
}

Returns this:

Array
(
    [0] => 10000-20000
    [1] => 30000-40000
)

This works great but now I have to explode each array part for an output like this:

Array
(
  [0] => Array (
     [0] => 10000
     [1] => 20000
  )
  [1] => Array (
     [0] => 30000
     [1] => 40000
  )
)
0

2 Answers 2

4

This should work, haven't tested.

$rArray = array();

foreach($rangesArray as $key=>$val) {
    $rArray[] = explode('-', $val);
}
Sign up to request clarification or add additional context in comments.

2 Comments

With respect, I think my answer is closer since it outputs a multi-dim array which is what you requested in your original question.
@user1477388 This iteration will also create a multi-dim array since it is assigning an array to each $rArray.
1

Just use another explode, this time like this: explode('-', $i);. You'll have to put it in a foreach like this:

$x = 0;
foreach ($rangesArray as $i)
{
  $arr = explode('-', $i);
  foreach ($arr as $j)
  {
    $arr1[$x] = $j;
  }
  $x++;
}

var_dump($arr1);

1 Comment

Accidentally deleted it, but ya, $x is not necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.