0
0
PHPprogramming~15 mins

Union types in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Union Types in PHP
📖 Scenario: You are building a simple PHP program that handles user input which can be either a number or a text message. You want to accept both types safely using PHP's union types feature.
🎯 Goal: Create a function that accepts a parameter which can be either an int or a string. The function will return a message describing the type and value received.
📋 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() to check if the input is an integer.
Return a string 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
Union types help PHP programs accept multiple types safely, which is common when handling user input or data from different sources.
💼 Career
Understanding union types is important for writing flexible and type-safe PHP code, a skill valued in modern PHP development jobs.
Progress0 / 4 steps
1
Create the describeInput function with a union type parameter
Write a 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 function describeInput(int|string $input): string to declare the function with a union type parameter.

2
Add type checking inside the function
Inside the describeInput function, use is_int($input) to check if $input is an integer. If it is, return the string "Input is an integer: " concatenated with the value of $input. Otherwise, return "Input is a string: " concatenated with $input.
PHP
Need a hint?

Use if (is_int($input)) { ... } else { ... } to check the type and return the correct message.

3
Call the function with an integer and a string
Call the describeInput function twice: once with the integer 42 and once with the string "hello". Store the results in variables $result1 and $result2 respectively.
PHP
Need a hint?

Call the function with 42 and "hello" and save the results in $result1 and $result2.

4
Print the results
Print the values of $result1 and $result2 each on a new line using echo.
PHP
Need a hint?

Use echo $result1 . "\n"; and echo $result2 . "\n"; to print each result on its own line.