PHP Tutorial: Determine Zodiac Sign from Birthdate
This PHP tutorial explains how to calculate a person's zodiac sign from their birthdate by parsing the date, handling single‑digit days, and using a series of if‑elseif or switch statements to map month‑day ranges to the twelve astrological signs.
The article presents a PHP program that determines a student's zodiac sign based on their birthdate, covering requirement analysis, design thinking, necessary PHP knowledge, implementation code, and result display.
Requirement analysis : The zodiac is matched to the month‑day range of the birthdate (e.g., March 21 – April 19 corresponds to Aries).
Design thinking : Two challenges are addressed – ensuring that a day value less than 10 is padded with a leading zero to avoid comparison errors, and implementing the zodiac‑judgment logic.
Knowledge base : The article reviews PHP conditional statements, including if , ternary ?: , if...else , if...elseif...else , and switch , providing their syntax.
Code implementation :
1. Define variables to store student information:
$name = '王六'; // save student name
$birth = '2003-08-07'; // save student birthdate2. Split the birthdate string to obtain year, month, and day:
$temp = explode('-', $birth);
$stu_by = $temp[0];
$stu_bm = $temp[1];
$stu_bd = $temp[2];3. Get the current year, month, and day (not strictly required for zodiac but shown as example):
$cur_y = date('Y'); // full year
$cur_m = date('n'); // month without leading zero
$cur_d = date('j'); // day without leading zero4. Pad single‑digit day values with a leading zero:
if ($stu_bd < 10) {
$stu_bd = '0' . $stu_bd;
}5. Combine month and day into a comparable string:
$date = "$stu_bm.$stu_bd";6. Determine the zodiac sign using a chain of if…elseif statements (the same logic could be expressed with switch ):
if ($date >= 1.21 && $date <= 2.19) {
$const = '水瓶座';
} elseif ($date >= 2.20 && $date <= 3.20) {
$const = '双鱼座';
} elseif ($date >= 3.21 && $date <= 4.20) {
$const = '白羊座';
} elseif ($date >= 4.21 && $date <= 5.21) {
$const = '金牛座';
} elseif ($date >= 5.22 && $date <= 6.21) {
$const = '双子座';
} elseif ($date >= 6.22 && $date <= 7.22) {
$const = '巨蟹座';
} elseif ($date >= 7.23 && $date <= 8.23) {
$const = '狮子座';
} elseif ($date >= 8.24 && $date <= 9.23) {
$const = '处女座';
} elseif ($date >= 9.24 && $date <= 10.23) {
$const = '天秤座';
} elseif ($date >= 10.24 && $date <= 11.22) {
$const = '天蝎座';
} elseif ($date >= 11.23 && $date <= 12.21) {
$const = '射手座';
} else {
$const = '魔羯座';
}Result display : The computed zodiac constant is output, and an example screenshot of the result is shown in the original article.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.