Why Do PHP Array Examples Leave a Trailing Comma

Why do PHP Array Examples Leave a Trailing Comma?

Why do PHP Array Examples Leave a Trailing Comma?

Because they can. :) The PHP Manual entry for array states:

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

Seriously, this is entirely for convenience so you can easily add another element to the array without having to first add the trailing comma to the last entry.

Speaking of other languages: Be careful with this in JavaScript. Some older browsers will throw an error, though newer ones generally allow it.

No comma after last element in array?

It is a style preference as mentioned elsewhere, however I would advise to condition yourself against adding that trailing comma in PHP, as it is syntactically invalid in some languages. In particular, I'm thinking of Internet Explorer's handling of those types of trailing commas in Javascript, which are notoriously difficult bugs to locate when scripts fail in IE while succeeding everywhere else. It will also break JSON's validity, and is invalid in a SQL SELECT list, among other potential problems.

Again, it's a matter of preference, but could cause you problems in other areas.

Delete Trailing Comma

You issue is that you are putting the trailing comma in there yourself. Try something like this:

<?php
$cars = array(
"Dodge" => array("Avenger","Challenger","Charger","Dart"),
"Toyota" => array("Highlander","Tundra","Corolla"),
"Nissan" => array("Sentra","Altima","Maxima")
);

echo "Make: Toyota";
echo "<br><br>";

$first = TRUE;
$carString = '';
foreach($cars['Toyota'] as $x){
if ($first){
$carString .= $x;
$first = FALSE;
}else{
$carString .= ", $x";
}
}
echo $carString;
?>

If you want a simpler loop, without the control structures (I felt it useful to demonstrate what is really going on in the loop), then you can use rtrim after looping, like this:

<?php
$cars = array(
"Dodge" => array("Avenger","Challenger","Charger","Dart"),
"Toyota" => array("Highlander","Tundra","Corolla"),
"Nissan" => array("Sentra","Altima","Maxima")
);

echo "Make: Toyota";
echo "<br><br>";

$carString = '';
foreach($cars['Toyota'] as $car) {
$carString .= $car.',';
}
echo rtrim($carString, ',');
?>

if you don't need to loop through for anything other than building the string, you can just implode the array to print it:

<?php
$cars = array(
"Dodge" => array("Avenger","Challenger","Charger","Dart"),
"Toyota" => array("Highlander","Tundra","Corolla"),
"Nissan" => array("Sentra","Altima","Maxima")
);

echo "Make: Toyota";
echo "<br><br>";
echo implode(', ', $cars['Toyota']);
?>

Remove trailing comma from line of text generated by final iteration of loop

  • If you have that array in a variable and want a string, you can use implode to get a string separated by a glue char.
  • If you already have an string, you can use rtrim to remove the last char to the right of the string.
  • If you have an array, where the value is a string ['Oct 13',1027] (ending in a comma), you have the same options above and:
    • You can use array_walk with some of the mentioned functions
    • You can get the last element, and use rtrim on it like the code below:

Example of code using rtrim on a array of strings:

<?php
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$lastIndex = count($values)-1;
$lastValue = $values[$lastIndex];
$values[$lastIndex] = rtrim($lastValue, ',');

Can you use a trailing comma in a JSON object?

Unfortunately the JSON specification does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.

In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:

s.append("[");
for (i = 0; i < 5; ++i) {
if (i) s.append(","); // add the comma only if this isn't the first entry
s.appendF("\"%d\"", i);
}
s.append("]");

That extra one line of code in your for loop is hardly expensive...

Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).

Doesn't work well with an array unfortunately.

int a[] = {1,2,}; Why is a trailing comma in an initializer-list allowed?

It makes it easier to generate source code, and also to write code which can be easily extended at a later date. Consider what's required to add an extra entry to:

int a[] = {
1,
2,
3
};

... you have to add the comma to the existing line and add a new line. Compare that with the case where the three already has a comma after it, where you just have to add a line. Likewise if you want to remove a line you can do so without worrying about whether it's the last line or not, and you can reorder lines without fiddling about with commas. Basically it means there's a uniformity in how you treat the lines.

Now think about generating code. Something like (pseudo-code):

output("int a[] = {");
for (int i = 0; i < items.length; i++) {
output("%s, ", items[i]);
}
output("};");

No need to worry about whether the current item you're writing out is the first or the last. Much simpler.

How do I remove the last comma from a string using PHP?

You may use the rtrim function. The following code will remove all trailing commas:

rtrim($my_string, ',');

The Second parameter indicates characters to be deleted.

Removing last comma from a foreach loop

Put your values in an array and then implode that array with a comma (+ a space to be cleaner):

$myArray = array();
foreach ($this->sinonimo as $s){
$myArray[] = '<span>'.ucfirst($s->sinonimo).'</span>';
}

echo implode( ', ', $myArray );

This will put commas inbetween each value, but not at the end. Also in this case the comma will be outside the span, like:

<span>Text1<span>, <span>Text2<span>, <span>Text3<span>

PHP - Getting content after last but one comma

explode, array_slice and implode can help you here:

function address($input) {
$parts = explode(",", $input);
$address = array_slice($parts, 0, count($parts) - 2);
$city_state = array_slice($parts, count($parts) - 2);
return array(trim(implode(",", $address)), trim(implode(",", $city_state)));
}

address("some street name, Seattle, WA");
// =>
Array
(
[0] => some street name
[1] => Seattle, WA
)

address("other street, number, something, Seattle, WA");
// =>
Array
(
[0] => other street, number, something
[1] => Seattle, WA
)


Related Topics



Leave a reply



Submit