Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 22, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

      July 22, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 22, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Write a PHP Script to Calculate the Area of a Triangle

    How to Write a PHP Script to Calculate the Area of a Triangle

    June 19, 2025

    In programming, being able to find the area of a triangle is useful for many reasons. It can help you understand logic-building and syntax, and it’s a common programming problem used in school assignments. There are also many real-world applications, such as computer graphics, geometry-based simulations, or construction-related calculations.

    In this article, we’ll look at a common problem: we are given the dimensions of a triangle, and our task is to calculate its area. You can calculate the area of a triangle using different formulas, depending on the information you have about the triangle. Here, you’re going to learn how to do it using PHP.

    After reading this tutorial:

    • You will understand the basic logic behind calculating the area of a triangle.

    • You will know how to write PHP code that calculates the triangle’s area using pre-defined and user-entered values.

    • You will know how to apply this logic in small projects and assignments.

    Table of Contents

    1. Prerequisites

    2. Find the Area of a Triangle Using Direct Formulas

    3. Find the Area of a Triangle Using the Base and Height Approach

    4. Find the Area of a Triangle Using Heron’s Formula

    5. Find the Area of a Triangle Using Two Sides and Included Angle (Trigonometric Formula)

    6. Conclusion

    Prerequisites

    You’ll understand this guide more easily if you have some knowledge about a few things:

    Basic PHP

    You’ll need to know basic PHP syntax to fully understand the problem. If you know how to write a simple echo statement or create a variable in PHP, then you should be good to go.

    Local PHP Environment

    To run the PHP code successfully, you should have local PHP development, such as XAMPP or WAMP, on your machine. You can also use online PHP editors like PHP Fiddle or OnlineGDB to run a PHP script without any installation.

    In this tutorial we are going to explore three approaches to determine the area of the triangle in PHP based on the amount of information available about the triangle.

    • Base and Height Formula Approach: This approach is applicable when you have the perpendicular height from the base and length of the base in the problem.

    • Heron’s Formula: This approach is used to calculate the area of triangle when you have the lengths of all three sides of the triangle.

    • Trigonometric Formula Approach: This approach is applied on the problem when you have the length of two sides and the included angle between them.

    First, let’s go back to math class and use some direct formulas to find the area.

    Find the Area of a Triangle Using Direct Formulas

    Example 1:

    In this first example, you’re given the input base and height of a triangle. You have to return the area of the triangle. For this example, you’ll use a direct formula to calculate the area of the triangle.

    Input:

    Base = 5,

    Height = 10

    You can calculate the area of the triangle using the formula:

    $$Area = (Base * Height) / 2$$

    So, if you plug in the values you have, you get: (5* 10) / 2 = 25.

    Output:

    Area = 25

    Example 2:

    In this second example, you’re given the length of two sides of a triangle and one angle between them. You have to return the area of the triangle. In this example, you’ll use another direct formula to calculate the area of the triangle.

    Input:

    Side A = 7, Side B = 9, Angle between them = 60°

    In this case, you’ll use the formula:

    $$Area = (1/2) A B * sin(Angle).$$

    Then just substitute in the values you’ve been given to find the area.

    Output:

    Area = 27.33 (approximately)

    Now let’s look at some different approaches to finding the area of a triangle using PHP.

    Find the Area of a Triangle Using the Base and Height Approach

    This is the simplest and most direct approach for calculating the area of a triangle when you know the base and height. In this approach, you’ll directly put values in the formula and find the area of the triangle – but you’ll do it with PHP code.

    First, define the base and height of the triangle. Then apply the formula for the area of the triangle. As we saw above, the formula for the area of a triangle is:

    $$Area = (Base * Height) / 2$$

    After calculating the area of the triangle, output the answer.

    Alright, so here’s how we can implement that in PHP:

    <?php
    // Define the base and height
    $base = 5;
    $height = 10;
    
    // Calculate the area
    $area = ($base * $height) / 2;
    
    // Output the result
    echo "The area of the triangle is: " . $area . " square units.";
    ?>
    

    Output:

    The area of the triangle is 25 square units.

    In the above code, first we initialize the base and height of triangle in two variables. Then we plug those values into the area formula. PHP calculates the area of the triangle and displays the answer.

    Time Complexity: In the above approach, we are using the direct formula to calculate and return the area of the triangle, so the time complexity will be constant at O(1). The constant time complexity is efficient as it will remain constant, regardless of the size or values of the base and height.

    Space Complexity: The Space Complexity will be O(1). The space used by the above program is constant, which ensures minimal use of memory. This space complexity is ideal in environments where memory efficiency is a priority.

    We use the above approach when we have the length of the base and height of the triangle (whether directly given or easily measurable in a right angle triangle). This method works best for right-angled triangles.

    Find the Area of a Triangle Using Heron’s Formula

    Heron’s formula is named after a Greek mathematician named Heron of Alexandria. Heron’s formula is useful when you know the lengths of all three sides of the triangle and you want to calculate the area without needing the height. This formula works for any type of triangle, including scalene triangles (triangles with sides of all different lengths).

    Here’s Heron’s formula to calculate the area of a triangle:

    $$√s(s−a)(s−b)(s−c) ​$$

    Where:

    • s = semi-perimeter = (a+b+c)/2 is the semi-perimeter of the triangle.

    • a, b, and c are the lengths of the sides.

    First, we define the three sides of the triangle. Then, we check all three conditions of the Triangle Inequality Theorem which states that if the sum of two sides is greater than the third side, then it is a valid triangle, and the given sides can form a triangle.

    We can calculate the semi-perimeter of the triangle using the formula s = a+b+c/2. Then we can apply Heron’s formula to calculate the area. After calculating the area, then output the answer.

    Here’s how you can implement this in PHP:

    <?php
    // Define the sides of the triangle
    $a = 7;
    $b = 9;
    $c = 10;
    
    // Check if the sides form a valid triangle using the Triangle Inequality Theorem
    if (($a + $b > $c) && ($a + $c > $b) && ($b + $c > $a)) {
    
        // Calculate the semi-perimeter
        $s = ($a + $b + $c) / 2;
    
        // Calculate the area using Heron's formula
        $area = sqrt($s * ($s - $a) * ($s - $b) * ($s - $c));
    
        // Output the result
        echo "The area of the triangle is: " . $area . " square units.";
    
    } else {
        // If the sides can't form a valid triangle
        echo "The given sides do not form a valid triangle.";
    }
    ?>
    

    Output:

    The area of the triangle is: 27.321 square units.

    In the above code, we first create three variables to store the lengths of the triangle’s sides, and check if the given sides form a valid triangle or not using the Triangle Inequality Theorem. Then we calculate the semi-perimeter using the formula: s = a + b + c / 2. We put the value of the semi-perimeter and lengths of all sides in Heron’s formula to calculate the area. The area of triangle is returned after calculating using the formula.

    Time Complexity: There is a total fixed number of operations such as addition, subtraction, multiplication, and square root. These operations don’t depend on input size as they are performed only a fixed number of times. This means that the time complexity is constant O(1).

    Space Complexity: We have used a fixed number of variables to calculate the area of the triangle. We have not used any additional data structures such as arrays or objects. The memory usage in the program is constant, which is better for low-memory environments. The space complexity is constant O(1).

    This approach works best when the lengths of all sides are given. This approach is used mainly for scalene or isosceles triangles where height is directly not given. This approach can work for any type of triangle, however – scalene, isosceles, or equilateral.

    Find the Area of a Triangle Using Two Sides and Included Angle (Trigonometric Formula)

    In this approach, we will see a different variation of the problem. When you know two sides of a triangle and the included angle between them, you can calculate the area using this formula:

    $$Area = 1/2 × a × b × sin(θ)$$

    Where:

    • a and b are the lengths of the two sides.

    • θ is the included angle between the two sides, measured in degrees or radians.

    Using the above formula, you can calculate the area of a triangle without needing its height. First, you define the two sides of the triangle and the angle between them. Then you convert the angle from degrees to radians if needed (in PHP, you can use deg2rad() to convert degrees to radians). Then you apply the formula.

    After calculating the area of the triangle, output the result.

    Here’s how to implement this in PHP:

    <?php
    // Define the two sides and the included angle
    $a = 7;
    $b = 9;
    $angle = 60; // Angle in degrees
    
    // Convert the angle from degrees to radians
    $angle_in_radians = deg2rad($angle);
    
    // Calculate the area using the formula
    $area = 0.5 * $a * $b * sin($angle_in_radians);
    
    // Output the result
    echo "The area of the triangle is: " . $area . " square units.";
    ?>
    

    Output:

    The area of the triangle is: 27.321 square units.

    Explanation:

    In the above case, we’re using the formula:

    Area of Triangle = 1/2 × a × b × sin(θ)

    And we’re substituting the following values into the formula:

    Area= 1/2 × 7 × 9 × sin(60 ∘) ≈ 27.321

    In the code, we declared two variables to store the length of the two sides of the triangle, and the variable $angle hold the included angle in degrees. We used deg2rad(), a PHP built-in function which converts an angle from degrees to radians. Then, we applied the actual formula: Area = 1/2 × 7 × 9 × sin(60 ∘). PHP stores the final answer in the $area variable.

    Time Complexity: We are using the direct formula to calculate the area of a triangle when the length of two sides and the angle between them are given. The constant time complexity is O(1).

    Space Complexity: Similarly, it does not take any extra space or use any data structures. It uses a single variable to store the result, which is why the space complexity is constant O(1).

    This approach is perfect for the problem in which two sides and the included angle (angle between those sides) are known. You can use it when you cannot easily calculate the height of the triangle. This problem has real-life applications in geometry problems, CAD applications, or physics simulations. This method is very accurate and doesn’t require the length of all sides.

    Conclusion

    In this article, you’ve learned how you can calculate the area of a triangle, both manually and using PHP. You have seen different approaches and learned about which one is best given the information you have. First, we discussed the base and height approach, then looked at Heron’s formula, and finally examined how to handle things when two sides and the included angle are given.

    Understanding the logic behind each of these approaches helps you choose the right one based on the given data.

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHow to Write Documentation That Increases Sign-ups
    Next Article Learn to Speak German

    Related Posts

    Development

    GPT-5 is Coming: Revolutionizing Software Testing

    July 22, 2025
    Development

    Win the Accessibility Game: Combining AI with Human Judgment

    July 22, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Digital Nomadism 9.0: The Rise of the Era of Freelancers

    Artificial Intelligence

    These 3 Microsoft Teams features are set to ship this summer — here’s why I’m excited

    News & Updates

    This Windows 11-like Linux distribution is aimed squarely at developers

    News & Updates

    Top 8 Retail Arbitrage Apps By Category

    Web Development

    Highlights

    CVE-2025-4363 – iSourcecode Gym Management System SQL Injection Vulnerability

    May 6, 2025

    CVE ID : CVE-2025-4363

    Published : May 6, 2025, 4:15 p.m. | 3 hours, 19 minutes ago

    Description : A vulnerability, which was classified as critical, has been found in itsourcecode Gym Management System 1.0. This issue affects some unknown processing of the file /ajax.php?action=end_membership. The manipulation of the argument rid leads to sql injection. The attack may be initiated remotely. The exploit has been disclosed to the public and may be used.

    Severity: 7.3 | HIGH

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    Adobe brings four highly-requested Premiere Pro AI features out of beta

    April 2, 2025

    Rilasciata GParted Live Live 1.7.0-8: Essenziale per la Gestione delle Partizioni

    July 14, 2025

    CVE-2025-6153 – PHPGurukul Hostel Management System SQL Injection Vulnerability

    June 17, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.