Search code examples
phparraysstringloopsconcatenation

How To convert array in string like to concate string with first array word like array[0].'->'.array[1]


$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
        'Users->User Departments->Department Hierarchy',
        'Settings->Registrar->Finance',
        'Logs->Second Opinion Log'];

This is array and I want to convert it into string like below The string should be one it just concate in one string.

Governance->Policies
Governance->Prescriptions
Governance->CAS Alerts

Users->User Departments
Users->Department Hierarchy

Settings->Registrar
Settings->Finance

Logs->Second Opinion Log
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
        'Users->User Departments->Department Hierarchy',
        'Settings->Registrar->Finance',
        'Logs->Second Opinion Log'];
$temp = '';
for($i = 0; $i < count($arr); $i++){
    $arrVal = [];
    
    $arrVal = explode('->',$arr[$i]);
    if(count($arrVal) > 1){
        for($j=0; $j < count($arrVal); $j++){
            if($j == 0){
                $temp .= $arrVal[$j];
            }else{
                $temp .='->'.$arrVal[$j]."\n";
                if($j == count($arrVal) - 1){
                    $temp .= "\n";
                }else{
                    $temp .= substr($temp, 0, strpos($temp, "->"));
                }
            }
        }
    }
 } 
 echo $temp;

Solution

  • Here the solution:

    <?php
    //This might help full
    $arr = ['Governance->Policies->Prescriptions->CAS Alerts',
            'Users->User Departments->Department Hierarchy',
            'Settings->Registrar->Finance',
            'Logs->Second Opinion Log'];
            
    $result="";
    $newline="<br>";
    foreach($arr as $data){
        $wordlist=explode('->',$data);
        $firstword=$wordlist[0];
        $temp='';
        foreach($wordlist  as $key=>$value){
          if($key > 0){
            $temp.=$firstword."->".$value.$newline;
          }
        }
        $temp.=$newline;
        $result.=$temp;
    }
    echo $result;
    ?>
    

    Output :

    Governance->Policies
    Governance->Prescriptions
    Governance->CAS Alerts
    
    Users->User Departments
    Users->Department Hierarchy
    
    Settings->Registrar
    Settings->Finance
    
    Logs->Second Opinion Log