Paul Paul - 7 months ago 27
PHP Question

Checking array count and then adding condition to add "and" to last array output

I have successfully create conditions which check the array count. Everything I have is working, but I am trying to figure out how to configure it so that if the results are:

1, 2, 3


I want it to be:

1, 2 and 3


How can I do this?

$proposal_type_arr = $_POST['prop-type'];
$proposal_type_count = count($proposal_type_arr);
if ($proposal_type_count == 1) {
$proposal_type = implode("", $proposal_type_arr);
}
else if ($proposal_type_count == 2) {
$proposal_type = implode(" and ", $proposal_type_arr);
}
else if ($proposal_type_count > 2) {
$proposal_type = implode(", ", $proposal_type_arr);
}

Answer Source

You could use array_pop() to grab the last element in the array. When combined with implode() you'd be able to cut down on the conditional logic.

Example:

$proposal_type_arr = $_POST['prop-type'];
$proposal_type_count = count( $proposal_type_arr );

if ( $proposal_type_count > 1 ) {
    $last_el = array_pop( $proposal_type_arr );
    $proposal_type = implode( ', ', $proposal_type_arr ) . ' and ' . $last_el;
} else {
    $proposal_type = current( $proposal_type_arr );
}