Created
February 20, 2023 05:46
-
-
Save ImtiazEpu/193952a149c2be886ff9006aaf9f766d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
//Q 1: Write a PHP function to sort an array of strings by their length, in ascending order. (Hint: You can use the usort() function to define a custom sorting function.) | |
function sort_arr_by_length($arr) { | |
usort($arr, function($a, $b) { | |
return strlen($a) - strlen($b); | |
}); | |
return $arr; | |
} | |
$fruits = array("apple", "banana", "pear", "orange", "mango"); | |
$arr = sort_arr_by_length($fruits); | |
print_r($arr); | |
//Q 2: Write a PHP function to concatenate two strings, but with the second string starting from the end of the first string. | |
function concat_strings_with_reverse($str1, $str2): string { | |
$str2_rev = strrev($str2); | |
return $str1 . $str2_rev; | |
} | |
$str1 = "Hello"; | |
$str2 = "World"; | |
$result = concat_strings_with_reverse($str1, $str2); | |
echo $result; | |
//Q 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_and_return_new_arr($arr) { | |
array_shift($arr); | |
array_pop($arr); | |
return $arr; | |
} | |
$fruits = array("apple", "banana", "pear", "orange", "mango"); | |
$new_arr = remove_first_last_element_and_return_new_arr($fruits); | |
print_r($new_arr); | |
//Q 4: Write a PHP function to check if a string contains only letters and whitespace. | |
function string_contains_only_letters_and_whitespace($str): bool|int { | |
return preg_match('/^[a-zA-Z\s]+$/', $str); | |
} | |
$str1 = "Hello world"; | |
$result = string_contains_only_letters_and_whitespace($str1); | |
print_r($result); | |
//Q 5: Write a PHP function to find the second-largest number in an array of numbers. | |
function second_largest_element($arr) { | |
$largest = $arr[0]; | |
$second_largest = $arr[0]; | |
$arr_length = count($arr); | |
for ($i = 1; $i < $arr_length; $i++) { | |
if ($arr[$i] > $largest) { | |
$second_largest = $largest; | |
$largest = $arr[$i]; | |
} elseif ($arr[$i] > $second_largest && $arr[$i] != $largest) { | |
$second_largest = $arr[$i]; | |
} | |
} | |
return $second_largest; | |
} | |
$arr = array(2, 5, 3, 8, 7); | |
$second_largest = second_largest_element($arr); | |
echo $second_largest; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment