
FizzBuzz, the quirky problem often thrown at developers in interviews, is not just about code; it's also an opportunity to have some fun with your programming skills. ๐คนโโ๏ธ
It involves printing numbers from 1 to a specified range with a few twists:
Traditionally, most solutions to FizzBuzz involve loops and conditional statements, but let's tackle it with a playful spirit and a touch of PHP 8 magic! ๐ฉ
In the conventional world of FizzBuzz, we typically use loops and custom functions to make the numbers dance to our tune. Here's the traditional choreography:
function FizzBuzz($number)
{
if ($number % 15 === 0)
return 'FizzBuzz';
if ($number % 3 === 0)
return 'Fizz';
if ($number % 5 === 0)
return 'Buzz';
return $number;
}
$results = [];
for ($number = 1; $number <= 100; $number++) {
$results[] = FizzBuzz($number);
}It's like choreographing a dance routine for each number. But what if we could make this dance more of a group performance? Let's introduce PHP's array functions to the stage.
array_map ๐ทCue the music, and let's simplify our code with a little jazz! ๐ถ
$results = array_map(function ($number) {
if ($number % 15 === 0) return 'FizzBuzz';
if ($number % 3 === 0) return 'Fizz';
if ($number % 5 === 0) return 'Buzz';
return $number;
}, range(1, 100));Now we have a snazzier and more expressive way to make our numbers dance together.
match Expression ๐ซBut wait, there's more! PHP 8 has a new move called match. It's like the latest dance craze that simplifies our FizzBuzz routine:
function FizzBuzz($number) {
return match (true) {
$number % 15 => "FizzBuzz",
$number % 3 => "Fizz",
$number % 5 => "Buzz",
default => $number
};
}
$results = [];
for ($number = 1; $number <= 100; $number++) {
$results[] = FizzBuzz($number);
}With match, it's as if our code is doing the FizzBuzz waltz effortlessly. ๐๐บ
Now, let's put on a show-stopping performance by merging the powers of array_map and match:
$results = array_map(function ($number) {
return match (true) {
$number % 15 => "FizzBuzz",
$number % 3 => "Fizz",
$number % 5 => "Buzz",
default => $number
};
}, range(1, 100));Our code is like a talented dancer who seamlessly blends different styles into a dazzling performance.
In conclusion, FizzBuzz isn't just a test of your coding skills; it's a chance to showcase your creativity and have some coding fun! So, when you face this classic challenge, don't forget to put on your favorite music, embrace PHP 8's features, and let your code dance!
Happy coding and keep grooving with PHP 8! ๐