0

Back to my original question, on how to check if the next elem starts with a space, if it does, concatenate it to the previous elem. how would you deal with cases where the array has multiple levels.

[1] => Array (
    [1] => Packages
    [2] => Sources
    [3] =>  Reading package
    [4] =>  Sources
    [5] =>  More Sources
    [6] => volatile Sources
    [7] =>  volatile
)

To output:

[2] => Array (
    [1] => Packages
    [2] => Sources Reading package Sources More Sources
    [6] => volatile Sources volatile
)

Will do it for the first space.

for($i = 0; $i < count($array); $i++){
    if($array[$i][0] == ' '){
        if($i > 0){
             $array[$i-1] .= $array[$i];
             unset($array[$i]);
        }
    }
}
5
  • 2
    What is your question? Iterating over an array and changing it is wrong! Commented Mar 14, 2011 at 14:37
  • 1
    stackoverflow.com/questions/5278119/… Commented Mar 14, 2011 at 14:39
  • So this is actually a duplicate? Commented Mar 14, 2011 at 14:43
  • Don't create a new question, clarify your original one instead.@kjy112 already provided a working solution to your original question. Commented Mar 14, 2011 at 14:49
  • @Felix i am pretty sure the question was solved, but not sure if OP knows Commented Mar 14, 2011 at 14:50

3 Answers 3

0
$t = array ( 'Packages',
             'Sources',
             ' Reading package',
             ' Sources',
             ' More Sources',
             'volatile Sources',
             ' volatile'
           );


$n = '';
foreach($t as $k => $v) {
    if (substr($v,0,1) == ' ') {
        $t[$n] .= $v;
        unset($t[$k]);
    } else {
        $n = $k;
    }
}

var_dump($t);
Sign up to request clarification or add additional context in comments.

Comments

0

If you can be sure that a particular character (e.g. |) is not present in any of your elements, you can do something like this:

$array = explode('|',str_replace('| ',' ',implode('|',$array)));

1 Comment

Don't I at least get cool points for getting it all on one line?
0

This should work (untested) :

$size = count($array);
for($i = 0; $i < $size; $i++){
    $space = true;
    for($j = $i + 1; $j < $size && $space; $j++) {
        $space = $array[$j][0] == ' ';
        if($space){
             $array[$i] .= $array[$j];
             unset($array[$j]);
        }
    }
}

Comments

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.