0
0
PHPprogramming~15 mins

Union types in practice in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Union types in practice
📖 Scenario: You are building a simple PHP program to handle user input that can be either a string or an integer. This is common when dealing with form data where users might enter numbers or text.
🎯 Goal: Create a PHP function that accepts a parameter which can be either an int or a string using union types. The function will return a message describing the type and value of the input.
📋 What You'll Learn
Create a function called describeInput that accepts a parameter with a union type int|string.
Inside the function, use is_int() and is_string() to check the type of the input.
Return a string message describing the input type and value.
Call the function with both an integer and a string and print the results.
💡 Why This Matters
🌍 Real World
Handling user input that can be multiple types is common in web forms and APIs. Union types help make your code clear and safe.
💼 Career
Understanding union types is important for writing modern PHP code that is robust and easy to maintain, a skill valued in backend development jobs.
Progress0 / 4 steps
1
Create the describeInput function with union type parameter
Write a PHP function called describeInput that accepts one parameter named $input with the union type int|string. Inside the function, just return an empty string "" for now.
PHP
Need a hint?

Use the syntax function describeInput(int|string $input): string to declare the function with a union type parameter.

2
Add type checks inside describeInput
Inside the describeInput function, add an if statement to check if $input is an integer using is_int($input). If true, return the string "Input is an integer: " concatenated with the value of $input. Add an elseif to check if $input is a string using is_string($input) and return "Input is a string: " concatenated with $input. Keep the function signature and the empty return removed.
PHP
Need a hint?

Use is_int() and is_string() to check the type and return the appropriate message.

3
Call describeInput with an integer and a string
After the function, write two lines of code that call describeInput with the integer 42 and the string "hello". Store the results in variables $resultInt and $resultStr respectively.
PHP
Need a hint?

Call the function with 42 and "hello" and save the results in $resultInt and $resultStr.

4
Print the results
Print the variables $resultInt and $resultStr each on its own line using echo. Use "\n" for new lines.
PHP
Need a hint?

Use echo $resultInt . "\n"; and echo $resultStr . "\n"; to print each result on a new line.