Finding the lengths of the largest and the smallest strings of the array

Hi,
I am trying to find the largest and the smallest lengths of the string but I am getting the same value. My code is:

<?php
$arr = array("abcd","abc","de","hjjj","g","wer");//array of strings
$arrsize = count($arr);
$shortest = $Largest = strlen($arr[0]);
for($i = 1; $i<arrsize; $i++){
      if ($Largest < strlen($arr[$i]))
         $Largest = strlen($arr[$i]);
}
for($i = 1; $i<arrsize; $i++){
      if ($shortest > strlen($arr[$i]))
         $shortest = strlen($arr[$i]);
}
echo "Largest = " . $Largest . "and Shortest  = " . $shortest;
?>

My output is:

Largest = 4and Shortest = 4

Somebody please guide me.

Zulfi.

Unless your assignment is to use loops, variables, and comparisons, just use php’s array functions to operate on the data as a set -

$arr = array("abcd","abc","de","hjjj","g","wer");

// get lengths (use php's strlen function as the call-back)
$len = array_map('strlen',$arr);

echo "Largest = " . max($len) . " and Shortest  = " . min($len);
1 Like

You omitted the “$” on $arrsize here and on line 9. It works when you correct that.

2 Likes

Also, you can combine those loops:

$arr = array("abcd","abc","de","hjjj","g","wer");//array of strings
$arrsize = count($arr);
$shortest = $Largest = strlen($arr[0]);
for($i = 1; $i<$arrsize; $i++){
      if ($Largest < strlen($arr[$i]))
         $Largest = strlen($arr[$i]);
      if ($shortest > strlen($arr[$i]))
         $shortest = strlen($arr[$i]);
}
echo "Largest = " . $Largest . "and Shortest  = " . $shortest;

And you could also use foreach rather than for:

$arr = array("abcd","abc","de","hjjj","g","wer");//array of strings
$shortest = $Largest = strlen($arr[0]);
foreach($arr as $word) {
      if ($Largest < strlen($word))
         $Largest = strlen($word);
      if ($shortest > strlen($word))
         $shortest = strlen($word);
}
echo "Largest = " . $Largest . "and Shortest  = " . $shortest;

You can then extract getting the length of the string over and over again, which is a pointless since it won’t change between calls:

$arr = array("abcd","abc","de","hjjj","g","wer");//array of strings
$shortest = $Largest = strlen($arr[0]);
foreach($arr as $word) {
      $wordLength = strlen($word);
      if ($Largest < $wordLength)
         $Largest = $wordLength;
      if ($shortest > $wordLength)
         $shortest = $wordLength;
}
echo "Largest = " . $Largest . "and Shortest  = " . $shortest;

And lastly you can get rid of the if statements by using the min and max functions:

$arr = array("abcd","abc","de","hjjj","g","wer");//array of strings
$shortest = $Largest = strlen($arr[0]);
foreach($arr as $word) {
      $wordLength = strlen($word);
      $Largest = max($Largest, $wordLength);
      $shortest = min($shortest, $wordLength);
}
echo "Largest = " . $Largest . "and Shortest  = " . $shortest;
1 Like

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