Last active
February 20, 2023 17:17
-
-
Save Rupashdas/2878b2e21113a7ef56a0d23ba4065350 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 1.Write a PHP function to sort an array of strings by their length, in ascending order. | |
function sort_strings_by_length($arrayItem) { | |
usort($arrayItem, function($a, $b) { | |
return strlen($a) - strlen($b); | |
}); | |
return $arrayItem; | |
} | |
$strings = array("apple", "banana", "cherry", "date", "elderberry"); | |
$sorted_strings = sort_strings_by_length($strings); | |
echo '<pre>'; | |
print_r($sorted_strings); | |
echo '</pre>'; | |
echo "\n"; | |
// 2.Write a PHP function to concatenate two strings, but with the second string starting from the end of the first string. | |
function concatenate_strings_reverse($string1, $string2) { | |
$len1 = strlen($string1); | |
$len2 = strlen($string2); | |
$new_string = substr($string1, 0, $len1-$len2) . strrev($string2); | |
return $new_string; | |
} | |
$string1 = "Hello World!"; | |
$string2 = "Hello Earth"; | |
$concatenated_string = concatenate_strings_reverse($string1, $string2); | |
echo "<pre>"; | |
echo $concatenated_string; | |
echo "</pre>"; | |
echo "\n"; | |
// 3.Write a PHP function to remove the first and last element from an array and return the remaining elements as a new array. | |
function remove_first_last_element($array) { | |
array_shift($array); | |
array_pop($array); | |
return $array; | |
} | |
$original_array = array(1, 2, 3, 4, 5); | |
$new_array = remove_first_last_element($original_array); | |
echo '<pre>'; | |
print_r($new_array); | |
echo '</pre>'; | |
echo "\n"; | |
// 4.Write a PHP function to check if a string contains only letters and whitespace. | |
function isLettersAndWhitespaceOnly($str) { | |
for ($i = 0; $i < strlen($str); $i++) { | |
$char = $str[$i]; | |
if (!ctype_alpha($char) && !ctype_space($char)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
$string = "This is a string with only letters and whitespace"; | |
if (isLettersAndWhitespaceOnly($string)) { | |
echo "letters and whitespace"; | |
echo "<\br>"; | |
echo "\n"; | |
} else { | |
echo " non-letter or non-whitespace"; | |
echo "<br>"; | |
echo "\n"; | |
} | |
//5.Write a PHP function to find the second largest number in an array of numbers. | |
function find_second_largest_number($array) { | |
rsort($array); | |
return $array[1]; | |
} | |
$numbers = array(4, 7, 2, 9, 5, 1, 8); | |
$second_largest_number = find_second_largest_number($numbers); | |
echo $second_largest_number; | |
echo "<\br>"; | |
echo "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment