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;