How to count items correctly?

Asked

Viewed 611 times

2

How can I change this code further down?

It takes the numeric values placed in Mysql in the medial table separated by comma placed in this way in the table 1,2,3,4,5,6,7,8,9,10. Then it counts the total of items placed in this table separated by a comma. If it has more than one comma-separated value the message appears in the plural otherwise it appears in the singular. But I’m having a problem: let’s say that the value inserted in Mysql is like this in the table medias: 1,. It places the message in the plural, not the singular. To remain singular, it is necessary that the inserted value is without the comma on the side, this way: 1.

How can I fix this?

<?php $contagem = explode(',', $episodios);
$count = count($contagem); ?>
<? if ($count == 1) { ?><div class="separadores"><div class="separador3">Ultimo Episodio Postado</div></div><? }else { ?><div class="separadores"><div class="separador3">Ultimos Episodios Postados</div></div><? } ?>
  • 1

    If an answer solved your problem you can accept it. See the [tour].

  • I’m just commenting to reinforce the @bigown comment. Your doubt today (well no, today, today) may be that of another person tomorrow and having an answer marked as resolved helps the process of assimilation of that someone. ;)

5 answers

5

Since you have a comma at the end of the string, PHP will count the 1, as two items, the first being the 1, and the second void.

The ideal would be to organize the DB not to have this type of inconsistency, but for existing data, the function trim() comes in handy as it removes characters from the ends of the strings, so the result will work well with or without a comma:

<?php
   $episodios = trim( $episodios, ', ' );
   $contagem = explode( ',', $episodios);
   $count = count($contagem);

   if ($count == 1) { ?>
      <div class="separadores"><div class="separador3">Ultimo Episodio Postado</div></div>
<? }else { ?>
      <div class="separadores"><div class="separador3">Ultimos Episodios Postados</div></div>
<? } ?>


Optimizing the code:

Since what changes is only the plural, it can be simplified in several ways. Here is a readable well:

<?php
   $episodios = trim( $episodios, ', ' );
   $contagem = explode( ',', $episodios);
   $pl = ( count($contagem) == 1 ) ? '' : 's';

   echo '<div class="separadores"><div class="separador3">';
   echo "Ultimo$pl Episodio$pl Postado$pl";
   echo '</div></div>';
?>

So, if it’s unique, $pl is empty, and if plural, $pl gets the lyrics s. You can do it without variables, simply changing the content of echo with the same logic.


If you prefer, use $count < 2 so that zero and one stay in the singular.

Discussion on the plural of "zero":
http://lgcooper.wordpress.com/2008/10/08/zero-e-plural-ou-singular/
http://www.ciberduvidas.com/idioma.php?rid=2837

  • Thank you very much for your help. I had put the question wrong because it was the other way around.

5

If you have the string in the variable $episodios ending with a , this will generate an empty input in the matrix.

A solution involves the use of the function array_filter() which allows you to clean the empty entries in the matrix:

$contagem = explode(',', "1,");

if (count(array_filter($contagem)) == 1) {
    echo '
    <div class="separadores">
        <div class="separador3">Ultimo Episodio Postado</div>
    </div>';
}
else {
    echo '
    <div class="separadores">
        <div class="separador3">Ultimos Episodios Postados</div>
    </div>';
}

See example in Ideone.

  • 1

    Note: If for some bizarre reason string for 1, , the solution with array_filter() no longer applies because the space at the end of the string which goes to the second entry in the matrix will be considered as a valid entry because it effectively has something inside (the whitespace).

3

Counting amounts over strings is not a very recommended way.

The ideal is to place the ID of each episode in an Array. This way you check the length of the Array. If the length is longer than one you put in the plural.

If $contagem is a vector, you can get its length with the function Count, thus:

count($contagem);

This also facilitates the treatment of the case in which there is no episode (zero length).

Good luck!

2

<?php
    $contagem = explode(',', $episodios);
    $count = count($contagem);
    $mensagem = $count > 2 ? "Ultimos Episodios Postados" : "Ultimo Episodio Postado"; 
    ?>
    <div class="separadores"> <div class="separador3"> <?php echo $mensagem; ?> </div></div>
  • Thanks for the help more like I unintentionally put an error in the explanation in case it happens the reverse edited the question if you can help me new mind thank.

  • 1

    I corrected the answer, that way it works is easy, but it should have better solutions

  • If the program works as described, the only problem would be if it had nothing in $episodes

1

I want to suggest a more efficient approach that solves with a single line (good, more than one because of the readability here in the post) the problem using preg_split():

$parts = preg_split(

    '/(\d+),+/', $str, -1,

    PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);

With this, just count the returned array and make the condition.

Now the explanation.

The difference between using preg_split() and use explode() is that the maximum control that explode() offers you is the amount of breaks she will accomplish.

Already preg_split() after the break already allows to automatically filter empty values through the bitmask flag PREG_SPLIT_NO_EMPTY combined as PREG_SPLIT_DELIM_CAPTURE

The pattern sought are numbers (\d+) separated by a comma, but in the resulting array we only want the numbers, so we guess a group ((\d+)) so that the first flag have what to capture.

Only with that we already have a success break, but with several empty indexes and that’s where the second comes in flag to ignore them.

And whether there is a comma after the last number in the list or not and whether the string is misshapen with more than one comma between each number, the output will always be equal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.