Getting $pieceCount

$pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode (" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2

I have the code above.
There are 6 pieces of pizza in the code above.
let’s suppose that I don’t know how many pieces of pizza are there.
How can I know the number of the pieces of pizza?
The code below work fine but it is, you think, foolish.

if( $pieces[9]=='') {$pieceCount=10;}
if( $pieces[8]=='') {$pieceCount=9;}
if( $pieces[7]=='') {$pieceCount=8;}
if( $pieces[6]=='') {$pieceCount=7;}
if( $pieces[5]=='') {$pieceCount=6;}
if( $pieces[4]=='') {$pieceCount=5;}
if( $pieces[3]=='') {$pieceCount=4;}
if( $pieces[2]=='') {$pieceCount=3;}
if( $pieces[1]=='') {$pieceCount=2;}
if( $pieces[0]=='') {$pieceCount=1;}

echo $pieceCount;

$pieces is an array. Arrays can be counted.

Expanding on the solution from @m_hutley above, you also need to take into account that you will find errors when running your original code, because you are be checking to see whether a non-existent array element has a certain value without checking whether or not that element exists. You’d get an undefined offset in a numerical array like this, or an undefined index in an associative array.

So in addition, have a look at isset, which can be wrapped around any reference to a variable that might not exist.

Run with for loop, total is count($pizza), you can get number of pizza.
This is your need?

Why is a for loop required to count the elements in an array?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.