0
0
PHPprogramming~15 mins

Why functions are needed in PHP - See It in Action

Choose your learning style9 modes available
Why functions are needed
📖 Scenario: Imagine you are writing a PHP program to calculate the area of different rectangles multiple times. Instead of writing the same calculation again and again, you can use a function to do it once and reuse it.
🎯 Goal: Build a simple PHP program that uses a function to calculate the area of rectangles. This will show why functions are useful to avoid repeating code and make programs easier to read and maintain.
📋 What You'll Learn
Create a function named calculateArea that takes two parameters: width and height.
Call the function calculateArea with different width and height values.
Store the results in variables.
Print the area results using echo.
💡 Why This Matters
🌍 Real World
Functions are used in all programming to organize code into reusable blocks. For example, calculating areas is common in graphics, games, and engineering software.
💼 Career
Understanding functions is essential for any programming job because they help write clean, efficient, and reusable code.
Progress0 / 4 steps
1
Create variables for width and height
Create two variables called width and height and set them to 5 and 10 respectively.
PHP
Need a hint?

Use $width = 5; and $height = 10; to create the variables.

2
Create the function calculateArea
Create a function named calculateArea that takes two parameters: width and height. The function should return the product of width and height.
PHP
Need a hint?

Define the function with function calculateArea($width, $height) and return the multiplication.

3
Call the function with different values
Call the function calculateArea with the variables $width and $height and store the result in a variable called $area1. Then call the function again with values 7 and 3 and store the result in $area2.
PHP
Need a hint?

Use $area1 = calculateArea($width, $height); and $area2 = calculateArea(7, 3);.

4
Print the results
Use echo to print the values of $area1 and $area2 on separate lines.
PHP
Need a hint?

Use echo $area1 . "\n"; and echo $area2 . "\n"; to print the results.