Horje
How to get first 3 longest words from a sentence PHP
The solution would be like this:
  • Use explode() to get the words of the string in an array
  • "Partially" sort the array elements in descending order of length
  • Use a simple for loop to print the longest three words from the array.

So your code should be like this:


Method - 1

See the Example.

index.php
Example: PHP
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$count = count($arr);
for($i=0; $i < $count; $i++){ $max = $arr[$i]; $index = $i; for($j = $i + 1; $j < $count; ++$j){ if(strlen($arr[$j]) > strlen($max)){ $max = $arr[$j]; $index = $j; } } $tmp = $arr[$index]; $arr[$index] = $arr[$i]; $arr[$i] = $tmp; if($i == 3) break;
}
// print the longest three words
for($i=0; $i < 3; $i++){ echo $arr[$i] . '<br />';
}
?>

Output should be:

Method - 2

Alternative method: (Using predefined functions)

index.php
Example: PHP
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr,function($a, $b){ return strlen($b)-strlen($a);
});
$longest_string_array = array_slice($arr, 0, 3);
// display $longest_string_array
var_dump($longest_string_array);
?>

Output should be:

Method - 3

See my Example.

index.php
Example: PHP
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$count = count($arr);
for($i=0; $i < $count; $i++){ $max = $arr[$i]; $index = $i; for($j = $i + 1; $j < $count; ++$j){ if(strlen($arr[$j]) > strlen($max)){ $max = $arr[$j]; $index = $j; } } $tmp = $arr[$index]; $arr[$index] = $arr[$i]; $arr[$i] = $tmp; if($i == 3) break;
}
// print the longest three words
for($i=0; $i < 3; $i++){ $long .= $arr[$i] . ' ';
}
echo $long;
?>

Output should be:

Method - 4

You need to create your own comparative function and pass it with array to usort php function. Ex.:


<?php
function lengthBaseSort($first, $second) { return strlen($first) > strlen($second) ? -1 : 1;
}
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr, 'lengthBaseSort');
var_dump(array_slice($arr, 0, 3));

It will output 3 longest words from your statement.

According to author changes :

If you have no ability to use usort for some reasons (may be for school more useful a recursive function) use following code:


<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
function findLongest($inputArray) { $currentIndex = 0; $currentMax = $inputArray[$currentIndex]; foreach ($inputArray as $key => $value) { if(strlen($value) > strlen($currentMax)){ $currentMax = $value; $currentIndex = $key; } } return [$currentIndex, $currentMax];
}
for($i = 0; $i < 3; $i++) { $result = findLongest($arr); unset($arr[$result[0]]); var_dump($result[1]);
}
?>

Output should be:





php extract

Type :
Develop
Category :
Web Tutorial
Sub Category :
PHP String Tutorial
Uploaded by :
Admin