I have an array which has several numbers. What I want to do is get a loop and run into this array and count how many two-digits numbers, three-digits, four-digits numbers do I have.
What I have tried:
$myArray = array(123,1234,12345,123456,123567);
for($i=1,$size=count($myArray);$i<=$size;i )
{
if(strlen($i==3)) echo "the number with index " .$i. " is three-digit number.";
else if(strlen($i==4)) echo "the number with index " .$i. " is four-digit number.";
...
}
I also tried this:
$threeDigits=0;
$fourDigits=0;
$fiveDigits=0;
$sixDigits=0;
$myArray=(123,1234,12345,123456,1234567,111,222)
for($i=1,$size=count($myArray);$i<=$size;i )
{
if(strlen($==3)) $threeDigits ;
else if(strlen($i==4)) $fourDigits ;
else if(strlen($i==5)) $fiveDigits ;
else if(strlen($i==6)) $sixDigits ;
}
echo "There are " .$fourDigits. " numbers with 4 digits.";
echo "There are " .$threeDigits. " numbers with 3 digits.";
echo "There are " .$fiveDigits. " numbers with 5 digits.";
echo "There are " .$sixDigits. " numbers with 6 digits.";
But somehow it only reads them as one. As you can see, in my array there are three three-digit numbers but when I print it out it says I have only one. What do you think it might be the problem here?
CodePudding user response:
Just for the hell of it, map it as a callback:
foreach(array_map('strlen', $myArray) as $key => $len) {
echo "the number with index $key is a $len digit number.";
}
CodePudding user response:
Store the lengths in an array:
$myArray = array(123,1234,12345,123456,123567);
$lengths = [];
foreach ( $myArray as $val ) {
$lengths[strlen($val)] ;
}
foreach (range(2,4) as $len) {
echo "There are " . $lengths[$len] . " $len-digit numbers\n";
}