skip to Main Content

string : The effect of leadership on work motivation

how to make the string to be like this:

Arrays
(
     [0] => The effect
     [1] => effect of
     [2] => of leadership
     [3] => leadership on
     [4] => on work
     [5] => work motivation
)

3

Answers


  1. One way is to explode and then loop to make desired array… have a look at code…


    $str = "The effect of leadership on work motivation";
    $explodedStringArray = explode(" ",$str);
    $arrayLength = count($explodedStringArray);
    $newStringArray = array();
    
    foreach ($explodedStringArray as $key => $value) {
    
        if($key != ($arrayLength-1)){
             $newStringArray[] = $value .' '. $explodedStringArray[$key+1] . '<br>';
        }
       
    }
    
    echo "<pre>";
    print_r($newStringArray);
    echo '</pre>';
    
    

    Result:

    Array
    (
        [0] => The effect
    
        [1] => effect of
    
        [2] => of leadership
    
        [3] => leadership on
    
        [4] => on work
    
        [5] => work motivation
    
    )
    
    Login or Signup to reply.
  2. Explode your initial string on <space>, then iterate along the resulting array, creating new strings from the result.

    
    <?php
    
    $str ="the effect of leadership on work motivation";
    $words =explode(" ",$str);
    $strings = [];
    for ($i=0;$i<count($words)-2;$i++) {
    $strings[]=$words[$i]." ".$words[$i+1];
    }
    print_r($strings);
    
    

    Output:

    Array
    (
        [0] => the effect
        [1] => effect of
        [2] => of leadership
        [3] => leadership on
        [4] => on work
    )
    

    See https://3v4l.org/Flgl0

    Login or Signup to reply.
  3. A possible solution:

    <?php
    
    $string = "The effect of leadership on work motivation";
    
    $couples = explode (' ', $string);  // not really couples yet
    
    foreach ($couples as $ind => $word) {
        
        if ($ind)
            $couples[$ind - 1] .= " $word";
    }
    
    if (count ($couples) > 1)
        array_pop($couples);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search