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

      Representative Line: Brace Yourself

      September 18, 2025

      Beyond the Pilot: A Playbook for Enterprise-Scale Agentic AI

      September 18, 2025

      GitHub launches MCP Registry to provide central location for trusted servers

      September 18, 2025

      MongoDB brings Search and Vector Search to self-managed versions of database

      September 18, 2025

      Distribution Release: Security Onion 2.4.180

      September 18, 2025

      Distribution Release: Omarchy 3.0.1

      September 17, 2025

      Distribution Release: Mauna Linux 25

      September 16, 2025

      Distribution Release: SparkyLinux 2025.09

      September 16, 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

      AI Momentum and Perficient’s Inclusion in Analyst Reports – Highlights From 2025 So Far

      September 18, 2025
      Recent

      AI Momentum and Perficient’s Inclusion in Analyst Reports – Highlights From 2025 So Far

      September 18, 2025

      Shopping Portal using Python Django & MySQL

      September 17, 2025

      Perficient Earns Adobe’s Real-time CDP Specialization

      September 17, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Denmark’s Strategic Leap Replacing Microsoft Office 365 with LibreOffice for Digital Independence

      September 19, 2025
      Recent

      Denmark’s Strategic Leap Replacing Microsoft Office 365 with LibreOffice for Digital Independence

      September 19, 2025

      Valve Survey Reveals Slight Retreat in Steam-on-Linux Share

      September 18, 2025

      Review: Elecrow’s All-in-one Starter Kit for Pico 2

      September 18, 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:

    <span class="hljs-meta"><?php</span>
    <span class="hljs-comment">// Define the base and height</span>
    $base = <span class="hljs-number">5</span>;
    $height = <span class="hljs-number">10</span>;
    
    <span class="hljs-comment">// Calculate the area</span>
    $area = ($base * $height) / <span class="hljs-number">2</span>;
    
    <span class="hljs-comment">// Output the result</span>
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"The area of the triangle is: "</span> . $area . <span class="hljs-string">" square units."</span>;
    <span class="hljs-meta">?></span>
    

    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:

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

    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:

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

    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

    AI Momentum and Perficient’s Inclusion in Analyst Reports – Highlights From 2025 So Far

    September 18, 2025
    Development

    Shopping Portal using Python Django & MySQL

    September 17, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Set up custom domain names for Amazon Bedrock AgentCore Runtime agents

    Machine Learning

    Multimodal AI on Developer GPUs: Alibaba Releases Qwen2.5-Omni-3B with 50% Lower VRAM Usage and Nearly-7B Model Performance

    Machine Learning

    Cybersecurity Must Lead, Not Lag, ASEAN’s Digital Transformation

    Development

    CVE-2025-7913 – TOTOLINK T6 MQTT Service Buffer Overflow Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    CVE-2025-5184 – Summer Pearl Group Vacation Rental Management Platform HTTP Response Header Handler Information Disclosure

    May 26, 2025

    CVE ID : CVE-2025-5184

    Published : May 26, 2025, 12:15 p.m. | 4 hours, 41 minutes ago

    Description : A vulnerability was found in Summer Pearl Group Vacation Rental Management Platform up to 1.0.1. It has been classified as problematic. Affected is an unknown function of the component HTTP Response Header Handler. The manipulation leads to information disclosure. It is possible to launch the attack remotely. Upgrading to version 1.0.2 is able to address this issue. It is recommended to upgrade the affected component.

    Severity: 4.3 | MEDIUM

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

    Taylor Swift hacked, but denies naked pictures will be leaked

    April 9, 2025

    CVE-2025-51672 – PHPGurukul Dairy Farm Shop Management System SQL Injection

    June 26, 2025

    OttoKit WordPress Plugin with 100K+ Installs Hit by Exploits Targeting Multiple Flaws

    May 15, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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