PHP Arrays Printing an Array with Commas - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Arrays Printing an Array with Commas - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, May 18, 2019

PHP Arrays Printing an Array with Commas

PHP Arrays





Printing an Array with Commas

Problem

You want to print out an array with commas separating the elements and with an and before the last element if there are more than two elements in the array.

Solution

Use the array_to_comma_string() function shown in example, which returns the correct string.


Example.   array_to_comma_string( )

           function array_to_comma_string($array) {
                   switch (count($array)) {
                   case 0:
                          return ' ' ;

                   case 1:
                          return reset($array);

                   case 2:
                          return join(' and ', $array);

                   default:
                          $last = array_pop($array);
                          return join(', ', $array) . ", and $last";
                   }
           }

Discussion

If you have a list of items to print, it’s useful to print them in a grammatically correct fashion. It looks awkward to display text like this:

            $thundercats = array('Lion-O', 'Panthro', 'Tygra', 'Cheetara', 'Snarf');
            print 'ThunderCat good guys include ' . join(', ', $thundercats) . '.';


This implementation of this function isn’t completely straightforward because we want array_to_comma_string() to work with all arrays, not just numeric ones beginning at 0. If restricted only to that subset, for an array of size one, you return $array[0].

But if the array doesn’t begin at 0, $array[0] is empty. So you can use the fact that reset(), which resets an array’s internal pointer, also returns the value of the first array element.

For similar reasons, you call array_pop() to grab the end element, instead of assuming it’s located at $array[count($array)-1]. This allows you to use join() on $array.

Also note that the code for case 2 actually works correctly for case 1, too. And the default code works (though inefficiently) for case 2; however, the transitive property doesn’t apply, so you can’t use the default code on elements of size 1.


No comments:

Post a Comment

Post Top Ad