-3

I've got a string and i wanted to put a word every after 5 words. The word is coming from array.

French History Maths Physics Spanish Chemistry Biology English DT Maths History DT Spanish English French RS

and i want to get 2 words from the array then insert it to the string above after 5 words.

$words = arrray(a, able, about, above, abst, accordance, according, accordingly, across, act, actually, added, adj);

Like this output :

French History Maths Physics Spanish a able about above abst Chemistry Biology English DT Maths according according accordingly across act Spanish English French RS.
  • 2
    Have you made any attempts at this yet, please add any code (non working code is fine) to the question. – Nigel Ren Jul 13 '20 at 06:00
  • I have made any attempts yet. i don't know how to start it. Thank you for replying to my question – Marc Justin Rait Jul 13 '20 at 06:01
  • but in your example, you add after every 5 words you add 5 words from the `array` instead of 2 or i misunderstanding? – Joseph Jul 13 '20 at 06:03
  • 2
    There are resources around for [php explode: split string into words by using space a delimiter](https://stackoverflow.com/questions/18638753/php-explode-split-string-into-words-by-using-space-a-delimiter) which is at least a start. – Nigel Ren Jul 13 '20 at 06:04
  • 1
    @Joseph Yes, but it's only the concept i wanted to show. sorry for inserting 5 words. – Marc Justin Rait Jul 13 '20 at 06:05
  • You need to show us your best attempt (code) so we can take it from there. Edit your question, so the output sample is in _accordance_ with your desired outcome as per your description (i.e. is it _a word_, or _2 words_, or a variable number?). – jibsteroos Jul 13 '20 at 06:28

1 Answers1

1
$string = 'French History Maths Physics Spanish Chemistry Biology English DT Maths History DT Spanish English French RS';
$words  = array('a', 'able', 'about', 'above', 'abst', 'accordance', 'according', 'accordingly', 'across', 'act', 'actually', 'added', 'adj');
$result = [];

$xpld = explode(' ',$string);
if(!empty($xpld))
{
  $count = 0;
  for ($i=0; $i < sizeof($xpld) ; $i++) 
  {
    if ($i % 5 == 0 && $i > 0) 
    {
      for ($j=$count; $j < $count + 5 ; $j++) 
      {
        $result[] = @$words[$j];
      }
      $count = $j;
    }
    $result[] = $xpld[$i];
  }
}
$result = implode(' ',$result);
echo $result;

The code above works like the one in your example, but I don't know is it efficient or not, note that I used suppress @ to avoid your array words out of index

xKobalt
  • 1,498
  • 2
  • 13
  • 19
moeha
  • 51
  • 5