phpstringreplacehuman-readable

Change format of an array of names from "last, first" to "first last"


I need to reverse the orientation of the first name and last name in an array of name strings.

$names = [
    "barira, stefan",
    "cikka, maria",
    "luppo, martin ",
    "bill, sebastian"
];

the output must be like this:

Array ( [0] => stefan, barira 
        [1] => maria, cikka 
        [2] => martin, luppo  
        [3] => sebastian, bill ) 

I got close with this code, but I want it to be like the output above:

$names = [
    "barira, stefan",
    "cikka, maria",
    "luppo, martin ",
    "bill, sebastian"
];
 
for ($i = 0; $i < count($names); $i++) {
    $words = $names[$i];
    $string = explode(' ', $words);
    $string = array_reverse($string);
    $reverse = implode(' ', $string);
    print_r($reverse);
}

Solution

  • This is what I would do

    $names = ["barira, stefan",
          "cikka, maria",
          "luppo, martin ",
          "bill, sebastian"];
    
    //note the & pass by reference, this way we don't even need a new array
    foreach($names as &$name)
      $name= implode(' ', array_reverse(array_filter(array_map('trim', explode(',', $name)))));
    
    print_r($names);
    

    Output

    Array
    (
        [0] => stefan barira
        [1] => maria cikka
        [2] => martin luppo
        [3] => sebastian bill
    )
    

    Sandbox

    I can explain what these functions do if you want...

    If you absolutely want that , back in there, which I think is a bad idea, you can just change this:

     $name = implode(', ', ...... );
    

    From a comment I made: it's probably a bad idea keeping that , in there. How will know it's been "reversed". Also the standard way is First Middle Last OR Last, First Middle

    PS. you can add ucwords() to uppercase the first letter of the names. Just wrap it around the implode, or before it's exploded