0

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?

7
  • I'm not sure of the metrics involved but perhaps sort the array first? Commented Sep 14, 2021 at 21:55
  • What does sorting helps here with? Commented Sep 14, 2021 at 22:00
  • Define "best"...what are you unhappy about in the current solution? It's hard to suggest an improvement unless you can describe a problem and/or a more specific goal Commented Sep 14, 2021 at 22:27
  • Hint: iterating over array is simplier with foreach -> foreach(myArray as key, value) or just foreach(myArray as value) Commented Sep 14, 2021 at 22:32
  • Near dupe: stackoverflow.com/a/1762216/2943403; I'll try to find a better one Commented Sep 14, 2021 at 22:57

2 Answers 2

0

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.";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, can you please take a look at my edited question? Maybe it will give you a clearer idea of what I want to achieve. I don't want the index of the two/three/four digit number, I want to count how many three/four/five-digit numbers I have.
-1

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";
}

Comments