How can I display an array in a human-readable format?

If I have an array that looks like this:

$str = '';
if( $_POST['first'] )
    $str = $_POST['first'];
if( $_POST['second'] )
    $str .= ($str != '' ? ',' : '') . $_POST['second'];
if( $_POST['third'] )
    $str .= ($str != '' ? ',' : '') . $_POST['third'];
if( $_POST['fourth'] )
    $str .= ($str != '' ? ',' : '') . $_POST['second'];
$str .= ($str != '' ? '.' : '');

Which gives me something like this:

Joe, Adam, Mike.

However, I would like to add " and " to the last element.

Therefore, he will read:

Joe, Adam, and Mike.

How can I change my code to do this?

+3
source share
3 answers

Arrays are good for this:

$str = array();
foreach (array('first','second','third','fourth') as $k) {
    if (isset($_POST[$k]) && $_POST[$k]) {
        $str[] = $_POST[$k];
    }
}
$last = array_pop($str);
echo implode(", ", $str) . " and " . $last;

You should probably have a special case above when there is one element. I actually wrote a function called "connection" that does the above and includes a special case:

function conjunction($x, $c="or")
{
    if (count($x) <= 1) {
        return implode("", $x);
    }
    $ll = array_pop($x);
    return implode(", ", $x) . " $c $ll";
}

Good question!

: :

function and_form_fields($fields)
{
     $str = array();
     foreach ($fields as $k) {
         if (array_key_exists($k, $_POST) && $v = trim($_POST[$k])) {
              $str[] = $v;
         }
     }
     return conjunction($str, "and");
}

...

and_form_fields(array("Name_1","Name_2",...));

$ _POST, .

+10

, , . , , aux.

, , 'and' aux.

0

Instead of publishing each individual variable, why not publish them as an array:

#pull the array from the POST:
$postedarray = $_POST['names'];

#count the number of elements in the posted array:
$numinarray = count($postedarray);

#subtract 1 from the number of elements, because array elements start at 0
$numinarray = $numinarray -1;

#set a prepend string
$prependstr = "and ";

#Pull the last element of the array
$lastname = $postedarray[$numinarray];

#re-define the last element to contan the prepended string
$postedarray[$numinarray] = "$prependstr$lastname";

#format the array for your requested output
$comma_separated = implode(", ", $postedarray);

print "$comma_separated";
0
source

Source: https://habr.com/ru/post/1710738/


All Articles