$data = explode(",", $str);
$names = array();
for ( $i = 0; $i < count($data); $i+=3) {
$names[] = $data[$i];
}
Suppose this gives the result:
mathews,neil,ambrose,glen,ethan
I want add and
just before ambrose
so the final result is:
mathews,neil, and ambrose
You should avoid loops for this kind of operation, they add an unnecessary level of complexity to your code.
// put the last element of $data to $lastName, and remove the last element from $data
$lastName = array_pop($names);
echo join(',',$names) . ' and ' . $lastName;
There are also many one line variations like this:
// replace the last ",name" with " and name"
echo preg_replace('/(,)[a-z]+$/', ' and ', join(',', $names));
But they wouldn't be very clear to inexperienced PHP developers.
edit, If you are happy to ditch the array you already have in your example, you can do this.
$str = "mathews,neil,ambrose,glen,ethan";
$names = array_slice(explode(',', $str), 0, 3);
$lastName = array_pop($names);
echo join(',', $names) . ' and ' . $lastName;
Since you're already using a counter $i
, you could just perform the following check:
if ($i === count($data) - 2) {
echo ' and ';
}
...or whatever. It doesn't have to be echo
.
$data = explode(",", $str);
for ($i = 0; $i<count($data)-1; $i++) {
$sentence = $sentence.$data[$i].", ";
}
$sentence = $sentence."and ".end($data).".";
echo $sentence;
What this will do is store all of the names except for the last one in a variable, with commas, and then at the end adds the last one with "and" before it.
That variable - $sentence - is then echoed (displayed).
EDIT: To only display the first three results is simple.
$data = explode(",", $str);
echo $data[0].", ".$data[1].", and ".$data[2];
The $data[x] simply returns one of the names, which are stored in order.