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
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
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>";
}
if($sentence == null)? When will $sentence ever be null? Wouldn't it make more sense to use strict comparison to what you manually assigned, === ''?Pretty simple lightweight solution
$array = array('apple','blue','red','green');
$str = '';
foreach($array as $item) {
$str = $str . ' ' . $item;
echo(ltrim($str) . '<br>');
}
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
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;
sizeof() in your for loop. Also, one foreach() loop should suffice.