2

Lets say I have a text file with 9 sentences (it could be more! this is just an example) , then i read that file in my php and split it every 3 sentence and store it in a variable so it result in this array:

$table = array(
   array(
        'text number 1',
        'text number 2',
        'text number 3'
    ),
   array(
        'text number 4',
        'text number 5',
        'text number 6'
    ),
   array(
        'text number 7',
        'text number 8',
        'text number 9'
    ),
 );

and then I want to add this string ('[br/]') between every array inside so it looks :

$table = array(
   array(
        'text number 1',
        'text number 2',
        'text number 3'
    ),

   '[br/]',  // <<< ---- the string here

   array(
        'text number 4',
        'text number 5',
        'text number 6'
    ),

   '[br/]',  // <<< ---- the string here

   array(
        'text number 7',
        'text number 8',
        'text number 9'
    ),
);

I've already tried this:

 foreach( $table as $key => $row )
  $output[] = array_push($row, "[br /]");

Which logically should have worked, but it hasn't.

Any help would be appreciated.

3 Answers3

3

You can just remap the array by using something like this:

$result = [];
foreach($table as $item) {
    $result[] = $item;
    $result[] = '[br/]';
}
SyncroIT
  • 1,510
  • 1
  • 14
  • 26
  • work like charm thank you sir , and also instead of muddling about the question like others , u answer directly and that's what i like , thanks also for that . greeting sir :) – kakashi senpai Nov 29 '17 at 17:24
2

http://php.net/manual/en/function.array-push.php

Gotta read the manual bro. array_push updates the first parameter that you pass in. So the correct syntax is something like this.

foreach( $table as $key => $row )
  array_push($output, $row, "[br /]");
bassxzero
  • 4,838
  • 22
  • 34
1

Reading your comment and trying to understand, what you´re trying to achieve, I would recommend you to read in all sentences in one array, then use

$chunks = array_chunk($input_array, 3);

to split it into your desired amount of sentences (e.g. 3) per array and afterwards iterate over it and implode each single array with <br> as glue.

$result = "";
foreach ($chunks as $chunk) {
    $result += implode("<br>", $chunk)
}
echo $result;
Chris P. Bacon
  • 533
  • 2
  • 15