tags:

views:

59

answers:

2

Hello,

I would like the value that has an o in the following example to be added to the key before the first key that has a value with an o in the array. Like this:

$arr = array(
0 => 'apple',
1 => 'pear',
2 => 'orange',
3 => 'octopus',
4 => 'pineapple'
)


$arr = array(
0 => 'apple',
1 => 'pearorangeoctopus',
2 => 'Pineapple'
)

But the amount of rows that has an o can be variable and multiple times in there..

$arr = array(

    0 => 'apple',
    1 => 'pear',
    2 => 'orange',
    3 => 'octopus',
    4 => 'pineapple',
    5 => 'blueberry',
    6 => 'pumpkin',
    7 => 'chocolate',
    8 => 'icecream'

)


$arr = array(
0 => 'apple',
1 => 'pearorangeoctopus',
2 => 'pineapple',
3 => 'blueberry',
4 => 'pumpkinchocolate',
5 => 'icecream'
)

anyone got an idea? :)

A: 

Try something like this:

$arr = array(...);

$new_arr = array();

$o_index = false;
foreach($arr as $key=>$item){
  if($item[0]=='o'){
    if(!$o_index)
      $o_index = $key-1;
    $new_arr[$o_index] .= $item
  }else{
    $new_arr[$key] = $item;
  }
}

Have in mind that this will make problems if your keys are not consecutive numbers or the first key starts with 'o'

Ilian Iliev
A: 
$result = array();
$currentIndex = 0;
$item = $arr[$currentIndex];
while ($currentIndex < count($arr)) {
    $nextItem = $arr[$currentIndex+1];
    if (strpos($nextItem, 'o') !== false) {
        $item .= $nextItem;
    }
    else {
        $result[] = $item;
        $item = $arr[$currentIndex+1];
    }
    $currentIndex++;
}

This is probably what you're looking for, if the solution for your second case is :

array(6) {
  [0]=> "apple"
  [1]=> "pearorangeoctopus"
  [2]=> "pineapple"
  [3]=> "blueberry"
  [4]=> "pumpkinchocolate"
  [5]=> "icecream"
}

BTW Just to be clear : the code needed to get rid of the Notice (Undefined offset) is left as an exercise.

wimvds