Happy Birthday PHP Script

29th October 2012 - 1 minute read time

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

Permalink

Alternative:

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

 

Stephan (Wed, 04/24/2013 - 15:37)

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');

Fra_T (Tue, 12/02/2014 - 10:21)

Permalink

Happiest wishes to you on this special day!!!

Allwin & Ashwin (Sun, 02/09/2020 - 04:53)

Permalink

Thank for the tips

Muili Muhammed (Sun, 10/25/2020 - 08:59)

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');

 

Anonymous (Wed, 11/04/2020 - 05:21)

Add new comment

The content of this field is kept private and will not be shown publicly.