Comma separated list from array with “and” before last element

后端 未结 6 1240
青春惊慌失措
青春惊慌失措 2020-12-11 05:43

I have an array ($number_list) that has a dynamically generated list of values. There will be at least 1 value in the array and no more than 4.

Currentl

相关标签:
6条回答
  • 2020-12-11 05:53
    $number_list = array(4, 5, 6, 7);    
    $comma_list = strrev(implode(strrev(', and'), explode(strrev(','), strrev(implode(', ', $number_list)), 2)));
    echo 'The list is ' . $comma_list . '.';
    

    Output: The list is 4, 5, 6, and 7.

    0 讨论(0)
  • 2020-12-11 05:56

    Remove the last element from the list, implode what's left with commas and then concatenate "and last_element":

    $last = array_pop($number_list);
    $output = implode(', ', $number_list);
    if ($output) {
        $output .= ', and ';
    }
    $output .= $last;
    

    If you prefer, you can also write the above more tersely as

    $last = array_pop($number_list);
    $output = $number_list
        ? implode(', ', $number_list).', and '.$last
        : $last;
    

    Update:

    I have to admit I initially misread the question and thought that it was about replacing the last comma with "and", not adding an "and" before the final item. I have since edited the answer to target the latter scenario. Note that the code can be easily adapted to do either by selecting " and " or ", and " for the "glue" string respectively.

    0 讨论(0)
  • 2020-12-11 05:57

    strrpos

    <?php
    
    $number_list= Array(1,2,3,4,5);
    $comma_list = implode(', ', $number_list);
    $comma_list = substr($comma_list,0,strrpos($comma_list,',')).' And'.substr($comma_list,strrpos($comma_list,',')+1);
    echo $comma_list;
    //returns 1, 2, 3, 4 And 5
    ?>
    
    0 讨论(0)
  • 2020-12-11 05:59

    Try array_pop() to get the last element, then array_push to modify and push the element back:

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

    Something like

    $last_element = array_pop($number_list);
    array_push($number_list, 'and '.$last_element);
    

    Then you can do your implode:

    $comma_list = implode(', ', $number_list);
    
    0 讨论(0)
  • 2020-12-11 06:11
    # pop the last element off the array and formate text
    if( count( $number_list )>1 ){
        $and = " and ".array_pop( $number_list );
    }else{
        $and = '';
    }
    # Implode number list , and  append $and
    $comma_list = implode(', ', $number_list).$and;
    
    0 讨论(0)
  • 2020-12-11 06:13

    If the list has at least two elements at the end, you can implode them with " and " (or if your question wasn't borked ", and ") already.

    Then you implode the whole array with ", ".

    • http://php.net/array_splice

    Example:

    <?php
    
    $numbers = range(1, 4);
    
    array_splice($numbers, -2, 2, implode(' and ', array_slice($numbers, -2)));
    
    echo implode(', ', $numbers); prints "1, 2, 3 and 4"
    

    Demo: https://eval.in/45277

    0 讨论(0)
提交回复
热议问题