PHP Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 48: Write a program to find the largest & smallest word in a string.

largest_smallest.php

<!DOCTYPE html>  
<html>  
<head>	
	<title>PHP Programs TutorialDuniya.com</title>
</head>

<body>
	<?php
		$str = "Hardships often prepare ordinary people for an extraordinary destiny.";  

		echo "Original string is  :- <br>  ". $str;

		$word = "";  
		$words = array();  
		$str = $str . " ";  

		for($i = 0; $i < strlen($str); $i++)
		{  
			if($str[$i] != ' ')
			{  
				$word = $word . $str[$i];  
			}  
			else
			{  
				array_push($words, $word);  
				$word = "";  
			}  
		}
	
		$small = $large = $words[0];
		for($k = 0; $k < count($words); $k++)
		{
			if(strlen($small) > strlen($words[$k]))  
				$small = $words[$k];  
		
			if(strlen($large) < strlen($words[$k]))  
				$large = $words[$k];  
		}  
	
		echo "Smallest word: " . $small;  
		echo "<br>Largest word: " . $large;    
	?>  
</body>  
</html>


If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.