简体   繁体   中英

How to display the number of items in an array in PHP

I'm using wordpress and based off the post I have an array of cards, each post will have a different number of cards in this array and I was wondering how I can show the number of cards in the array.

$class_cards[]=array('card_count'=>$card_count);

The total number of cards in this array will vary by post, so I want to be able to store the number of cards in a variable so I can echo it out later down the page.

Edit: Follow Up Question

I have a follow up to this question, I have a variable which is called $card_count which is stored in the array as you can see above. The card count will always be 1 or 2 saying that there is either one version of this card or two versions of this card. If there are two I would need to count that card twice in the overall number how can I do this with count($class_cards) ?

For example lets say I have a total of 9 cards in that array. The count would turn out as 9, but in that array 6 out of those 9 cards have 2 as their card count, while 3 has 1 as their card count. So the total number of cards should be 15 instead of 9.

You can do it in very simple way like

$count_cards = count($class_cards);

This will return you the count of the cards.

Hi i think this piece of code will help you if i got what you want

$count_cards = count($class_cards); // Total number of objects(cards) in an array in this  example  it  is 9 

foreach($class_cards AS $key => $value)
{
   //Assuming the card count as 9  this  loop will  run 9 times 
   if($value['card_count'] == 2)
   {
      $count_cards++; // Adding another card  if the card  count is  2
   }
}
echo $count_cards ; // Total number of cards , Should  echo 15 according to this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM