0

How to explode this string :

00004.00001.00003.00001.00003

in an array like this :

array (size=3)
  0 => string '00004' (length=5)
  1 => string '00004.00001' (length=10)
  2 => string '00004.00001.00003' (length=15)
  3 => string '00004.00001.00003.00001.00003' (length=20)

Thx

5
  • Do you mean to have 5 elements in the resulting array? It looks like the last element in your array breaks with the pattern you're after. Commented Nov 28, 2012 at 17:06
  • array (size=3)? Make sure your explanation is right please/ Commented Nov 28, 2012 at 17:07
  • It's probably some variable dump output, but not that of the commonly used print_r or var_dump. On topic: This is not so hard to do, what have you tried? Commented Nov 28, 2012 at 17:08
  • 1
    Explode, then a set of nested for loops to concatenate. Good luck with your homework. Commented Nov 28, 2012 at 17:09
  • Ho what a beautiful surprise at the wake up :) ok I answer even if I see the solution below : array (size=3) it's only a mistake a made when I wrote the question. Thx all Commented Nov 29, 2012 at 8:05

3 Answers 3

3
$array = explode('.', '00004.00001.00003.00001.00003');

foreach($array as $key => $value) {
  if($array[$key - 1]) {
    $array[$key] = $array[$key - 1] . '.' . $value;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Ceejayoz. This is the solution for my purpose. if(!empty($array[$key - 1])) remove error notice.
Yeah, some PHP error reporting settings will complain there. You can also do if(isset($array[$key - 1])).
0

Explode it first as you would normally do $arr = explode('.', $str); and then build desired array with two loops.

Comments

0

Another version using array_map() :

$arr = explode('.', '00004.00001.00003.00001.00003');
$arr[] = 'blank';
$array = array_map(function(){
     global $arr;
     array_pop($arr);
     return implode($arr);
}, $arr);

1 Comment

Thx for your answer. But this don't work. Here is the result I get : ` array (size=6) 0 => string '0000400001000030000100003' (length=25) 1 => string '00004000010000300001' (length=20) 2 => string '000040000100003' (length=15) 3 => string '0000400001' (length=10) 4 => string '00004' (length=5) 5 => string '' (length=0) `

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.