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.

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

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

Comments

Permalink

Alternative:

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

 

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

Permalink
Recursive alternative :P
  1. function singHappyBirthday($nm, $i = 0) {
  2.  
  3. printf("Happy birthday %s!\n", (2 === $i) ? "dear {$nm}" : "to you");
  4. return $i === 3 || singHappyBirthday($nm, ++$i);
  5.  
  6. }
  7. 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
  1. <?php
  2.  
  3. $string = '';
  4.  
  5. for ($i = 0; $i < 4; $i++) {
  6.  
  7. $string .= "Happy birthday ";
  8.  
  9. if ($i != 2) {
  10.  
  11. $string .= "to you!\n";
  12.  
  13. } else {
  14.  
  15. $string .= "dear %s!\n";
  16.  
  17. }
  18.  
  19. }
  20.  
  21. 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.