Happy Birthday PHP Script

When posting happy birthday messages to developers over social media I like to write it in code, just to be geeky. The following code will print the happy birthday song using PHP.

<?php
$string = '';
for ($i = 0; $i < 4; $i++) {
    $string .= "Happy birthday ";
    if ($i != 2) {
        $string .= "to you!\n";
    } else {
        $string .= "dear %s!\n";
    }
}
print sprintf($string, 'name');

This can be easily personalised by just changing the second parameter in the sprintf() function.

Comments

Alternative:

function singHappyBirthday($nm) {
  for ($i = 0; $i < 4; $i++) {
    printf("Happy birthday %s!\n", (2 === $i) ? "dear {$nm}" : "to you");
  }
}
singHappyBirthday('name');

 

Permalink
That's good! Thanks Stephan :)
Name
Philip Norton
Permalink
Recursive alternative :P function singHappyBirthday($nm, $i = 0) { printf("Happy birthday %s!\n", (2 === $i) ? "dear {$nm}" : "to you"); return $i === 3 || singHappyBirthday($nm, ++$i); } singHappyBirthday('name');
Permalink

Happiest wishes to you on this special day!!!

Permalink

Thank for the tips

Permalink
<?php

$string = '';

for ($i = 0; $i < 4; $i++) {

    $string .= "Happy birthday ";

    if ($i != 2) {

        $string .= "to you!\n";

    } else {

        $string .= "dear %s!\n";

    }

}

print sprintf($string, 'name');

 

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.