English 中文(简体)
PHP to form string like "A, B, C, and D" from array values
原标题:

Given the following array:

Array
(
    [143] => Car #1
    [144] => Car #2
    [145] => Car #3
)

I am currently using this

implode( ,  , array_values($car_names))

to generate a string like

Car #1, Car #2, Car #3

I would like to actually get something like

Car #1, Car #2 and Car #3

The idea would be to insert " and " between the two last elements of the array.

If the array happens to contain two key/value pairs (eg, user has 2 cars), there would be no commas.

Car #1 and Car #2

And if the array contains one key/value (eg, user has 1 car)

Car #1

Any suggestion how to get this done? I tried using array_splice but I m not sure that s the way to go (ie, inserting a new element into the array).

Thanks for helping!

最佳回答

I think you probably want something like this, using array_pop to get the last element off the end of the array. You can then implode the rest of the array, and add the last element in a custom fashion:

$last_value = array_pop($car_names);
$output = implode( ,  , array_values($car_names));
$output .= ($output ?   and   :   ) . $last_value;

Edit: added conditional to check if the array had only one element.

问题回答
$last = array_pop($car_names);
echo implode( ,  , $car_names) .   AND   . $last;

A preg_replace can look for the last command just just swap it to an and

$yourString = preg_replace( "/, ([w#]*)$/", "and 1", $yourString );

This solution is a bit longer, but tested for all array sizes and it is a complete solution. Also, it doesn t modify the array like the above answers and is separated into a function.

function arrayToString($arr) {
    $count = count($arr);
    if ($count <= 2) {
        return implode(  and  , $arr);
    }
    $result =   ;
    $i = 0;
    foreach ($arr as $item) {
        if ($i) $result .= ($i == $count - 1) ?   and   :  ,  ;
        $result .= $item;
        $i++;
    }
    return $result;
}

Compacted version with ugly formatting and ignoring good practices like initializing variables:

function arrayToString($arr) {
    if (count($arr) <= 2) return implode(  and  , $arr);
    foreach ($arr as $item) {
        if ($i) $result .= ($i == count($arr) - 1) ?   and   :  ,  ;
        $result .= $item; $i++;
    }
    return $result;
}

I m not sure there s a built in function for this, but something like this should work.

$last = $car_names[count($car_names)-1];
$implodedString = implode( ,  , array_values($car_names))
$implodedString = str_replace(", $last", "and $last", $implodedString);

That s an example with the functions named in my comment above:

  1. strrpos() - Find the position of the last occurrence of a substring in a string
  2. substr() - Return part of a string

and the code:

$text = implode( ,  , array_values($car_names));
$last = strrpos($text,  , );
if ($last) $text = substr($text, 0, $last-1) .   AND   . substr($text, $last+1);
echo $text;

There are a number of ways you could do this. Here s another.

<?php
$cars = array( Car #1 ,  Car #2 ,  Car #3 ,  Car #4 );
$car = array( Car #1 );
$twocars = array( Car #1 ,  Car #2 );

function arrayToText($arr) {
    switch (count($arr)) {
    case 1:
        return $arr[0];
        break;
    case 2:
        return implode($arr,   and  );
        break;
    default:
        $last = array_pop($arr);
        return implode($arr,  ,  ) .   and   . $last;
        break;
    }
}

echo  <p>  . arrayToText($cars) . "</p>
";
echo  <p>  . arrayToText($twocars) . "</p>
";
echo  <p>  . arrayToText($car) . "</p>
";

Output

<p>Car #1, Car #2, Car #3 and Array</p>
<p>Car #1 and Car #2</p>
<p>Car #1</p>




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签