0
0
PHPprogramming~15 mins

Function declaration and calling in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Function declaration and calling
📖 Scenario: You are creating a simple PHP program to greet users by their name. This is like writing a small helper that says hello whenever you ask it.
🎯 Goal: Build a PHP program that declares a function called greet which takes a name and returns a greeting message. Then call this function with a specific name and print the greeting.
📋 What You'll Learn
Declare a function named greet that accepts one parameter called name.
The function should return a string greeting in the format: "Hello, {name}!".
Call the greet function with the argument "Alice".
Print the result of the function call.
💡 Why This Matters
🌍 Real World
Functions help organize code into reusable blocks, like helpers that do one job well. This is common in all programming tasks.
💼 Career
Knowing how to declare and call functions is essential for any PHP developer to write clean, maintainable code.
Progress0 / 4 steps
1
Declare the greet function
Write a PHP function declaration named greet that takes one parameter called name. Inside the function, return the string "Hello, " concatenated with the name parameter and an exclamation mark "!".
PHP
Need a hint?

Use the function keyword, then the function name greet, and parentheses with $name inside. Use return to send back the greeting string.

2
Call the greet function with "Alice"
Create a variable called message and set it to the result of calling the greet function with the argument "Alice".
PHP
Need a hint?

Assign the result of greet("Alice") to the variable $message.

3
Print the greeting message
Use echo to print the variable message.
PHP
Need a hint?

Use echo $message; to display the greeting on the screen.

4
Run the program and see the output
Run the PHP script and observe the output. It should print Hello, Alice! exactly.
PHP
Need a hint?

Make sure you run the PHP file in a server or command line to see the output.