Loop & Function Problems
Loop & Function Problems
2. Prompt the user to enter the start and ending numbers and then prints the numbers from the start to the end.
3. Use for loop and array count() function to display the elements of the array $fruits.
$fruits = ['Apple','Banana','Cherry','Dates'];
$x = 10;
while ( $x >=2) {
echo "Number:" . $x . "\n";
$x-=2;
}
$x = 3;
$y = 7;
$x += 2;
$y -= 1;
}
$x = 5;
$y = 2;
$x -= 1;
$y += 2;
}
7. Print all even numbers from 2 to 20 using a do while loop.
$a = 2;
do {
if ($a %2==0) {
echo $a . ' ';
}
$a++;
} while ($a <= 20);
8. Calculate and print the sum of squares of numbers from 1 to 5 using a do-while loop.
$x= 1;
$sum= 0;
do{
$x1= $x ** 2;
$x++;
$sum = $sum + $x1;
echo $x1. " ";
}while($x <= 5);
9. Given an array of numbers, calculate and print the sum of all elements using a foreach loop.
10. Given an array, square each element and print the modified array using a foreach loop.
$numberz = [];
11. Given an associative array of prices, calculate and print the total cost using a foreach loop.
$prices = array(
'Apple' => 1.25,
'Banana' => 0.75,
'Cherry' => 2.50,
'Orange' => 1.00,
'Grapes' => 3.00
);
$sum=0;
foreach($prices as $key => $value){
}
echo "Sum: ". $sum;
12. Given an array of numbers, create a new array containing only the odd numbers using a foreach loop.
$numbers = [5, 10, 15, 20, 25];
$array = [];
foreach ($numbers as $odd) {
if ($odd % 2 == 1) {
array_push($array,$odd);
}
}
print_r($array);
function calculate($ediwow){
return strlen($ediwow);
}
14. Write a PHP program that defines a function extractSubstring($str, $start, $length) which takes a string $str, a starting position
$start, and a length $length. The function should return the substring starting from the specified position and having the
specified length.
Sample output:
Enter a string: The quick brown fox jumps over the lazy dog.
Enter the starting position: 4
Enter the length of the substring: 10
Substring: quick brown
15. Create a function that takes an amount and a tax rate as parameters and returns the total amount including tax. The tax should
be calculated as a percentage of the original amount.