-1

I have a PHP array and I want to split it into a custom sentence.

  $array = array('apple','blue','red','green');

I want the output below:

  apple
  apple blue
  apple blue red
  apple blue red green
2
  • 1
    That’s rather the opposite of splitting, you want to combine the array elements, to form some new output. What have you tried? Should be simple, using two nested for loops … Commented May 25, 2021 at 8:03
  • 1
    you could use a basic concatenation cycling your array elements Commented May 25, 2021 at 8:18

4 Answers 4

1

You could try this simple solution

$array = array('apple','blue','red','green');
$sentence = "";
foreach($array as $key) {
  if($sentence === ""){
    $sentence = $key;
  }
  else{
    $sentence = $sentence." ".$key;
  }
  echo $sentence;
  echo "</br>";
}
Sign up to request clarification or add additional context in comments.

5 Comments

Foreach is more efficient than for loop. Upvoting.
if($sentence == null)? When will $sentence ever be null? Wouldn't it make more sense to use strict comparison to what you manually assigned, === ''?
@El_Vanja yes and no. we are comparing is strings, and an empty string can be evaluated as "null". your suggestion is more strict, mine is a bit more loose. you can also look at stackoverflow.com/questions/624922/…
Code is clearer when it's explicit. There is no need for a loose comparison since you know exactly what you should be comparing to.
Edited the code, made it more explicit using your suggestion @El_Vanja
1

Pretty simple lightweight solution

    $array = array('apple','blue','red','green');
    $str = '';
    foreach($array as $item) {
        $str = $str . ' ' . $item;
        echo(ltrim($str) . '<br>');
    }

2 Comments

The only minor issue is that there will be a leading space here.
@El_Vanja Yeah thats true, can be solved by just adding a ltrim to it I guess
1

Use for-loop with array_slice to Extract a slice of the array each time, And use implode(glue, pieces) to join the values of the array with a space.

$array = array('apple','blue','red','green');
for ($i=1; $i <= count($array) ; $i++) { 
    echo implode(' ', array_slice($array, 0, $i))."</br>";
}

Prints:

apple
apple blue
apple blue red
apple blue red green

Comments

-1

This is very simple

$array = array('apple','blue','red','green');
$new = "";
for($i=0; $i<sizeof($array); $i++) {
  for($j=0; $j<=$i; $j++){
    $new .= $array[$j]." ";
  }
  $new .= "<br>";
}
echo $new;

1 Comment

it's not very efficient to use sizeof() in your for loop. Also, one foreach() loop should suffice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.