search

Calculating other roots like the nth root of a number, or cube root of a number, similarly, we need to find the square root of numbers in PHP. We calculate these roots by using different functions like pow(), log() and others.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In a programming language like PHP, calculating square root is simple when used with built-in function. This function is sqrt(). We will also see how to find the square root of a number without using sqrt() and how to calculate square root using a form with user input.

The sqrt() function is used to calculate the square root of a given number. This function is a built-in Math function used in PHP like pow(), rand(), is_nan() etc.

Square Root Logic

The syntax and description of square root logic is explained in details below,

Syntax:

sqrt($num)

Where $num is the single argument passed to the sqrt function.

Description: sqrt() function calculates and returns the square root of the given number. The returned value is of type float. Also, we have different types of input numbers to the given function on which the square root function is performed and the result is calculated.

Here we will see that the input numbers can be positive or negative numbers or decimal numbers (float) or it can also be zero. The positive numbers return positive numbers as output and negative numbers return NAN (Not a Number) as output, the square root of decimal numbers is a float as output, and the square root of one is one. Also, remember the square root of zero is zero.

Finding Square Root of a Given Number

The square root of a given number is as per the following,

If the input number is 81, the square root of the number will be 9. If the input number is 49, the square root number will be 7 and so on.

Let us learn this with an example:

We will also learn to find the square root with different types of input.

Example #1

Code:

<?php // simple example to find how sqrt() function works on numbers
echo sqrt(16);
echo '<br>';
// output is 4
echo sqrt(7);
echo '<br>';
//output is 2.6457513110646
?>

Output:

Square Root in PHP

In the above program, the output is 4 as we know 4*4 is 16 thus the square root of 16 is 4. While calculating the square root of 7, we see that after the decimal many digits are found, the number of digits after the decimal depends upon the user.

Similar to the sqrt function, which calculates the square root of the given number. To calculate any root of the given number we use pow() function which stands for power.

Example #2

Code :

<?php // example to calculate any root
echo '<br>'.'Result of  :   pow(16, 1/2)  ======  '. pow(16, 1/2);
// example to calculate the cube root of 27
echo '<br>'.'Result of  : pow(27, 1/3)  ======  '. pow(27, 1/3);
//example to calculate the fourth root of 12
echo '<br>'.'Result of  : pow(12, 1/4)  ======  '. pow(12, 1/4);
//example to calculate the fifth root of 76
echo '<br>'.'Result of  : pow(76, 1/5)  ======  '. pow(76, 1/5);
//example to calculate the sixth root of 88
echo '<br>'.'Result of  : pow(88, 1/6)  ======  '. pow(88, 1/6);
?>

Output:

Square Root in PHP

Example #3

Code:

<?php echo '<br>'.'Result of  :   sqrt(625)  ======  '. sqrt(625);
echo '<br>'.'Result of  :   sqrt(49)  ======  '. sqrt(49);
echo '<br>'.'Result of  :   sqrt(-36)  ======  '. sqrt(-36);
echo '<br>'.'Result of  :   sqrt(0)  ======  '. sqrt(0);
echo '<br>'.'Result of  :   sqrt(121)  ======  '. sqrt(121);
echo '<br>'.'Result of  :   sqrt(22)  ======  '. sqrt(22);
echo '<br>'.'Result of  :   sqrt(12.34)  ======  '. sqrt(12.34);
echo '<br>'.'Result of  :   sqrt(-16)  ======  '. sqrt(-16);
?>

Output:

Square Root in PHP

Example #4

Finding Square Root of A Number Entered by The User Through a Form: In the following program, we have created a program in PHP to calculate the square root of a number entered by the user through a form. Suppose the user has entered 16 then we can find the square root of the 16 and expect the result as 4, if the user entered 49 we can expect the result as 7 and so on.

Also, we have used the built-in mathematical function sqrt() to find the square root.

Code:

<!---program to calculate square root of input number using form -->


<title>Square root of a number using form</title>


<!--- input form with text box --->

Output – 1:

Square Root in PHP

Output – 2: With 100 as input.

Square Root in PHP

Example #5

Finding Square Root of A Number without Using Built-in sqrt() Function: In the following program, we have created a program in PHP to calculate the square root of a number without using built-in sqrt() function.

Code:

function squareroot($input)
{
//if the input number is 0 then return 0 as result
if($input == 0) {
return 0;
}
//if the input number is 1 then return 1 as result
if($input == 1) {
return 1;
}
// assigning $input value to a variable $a
$a = $input;
$b = 1;
while($a > $b)
{
// calculating the middle number
$a= ($a + $b)/2;
// dividing the input number with the middle number
$b = $input/$a;
}
return $a;
}
echo '<br>'.'Square root of 0 is '.squareroot(0);
echo '<br>'.'Square root of 20 is '.squareroot(20);
echo '<br>'.'Square root of 49 is '.squareroot(49);
echo '<br>'.'Square root of 81 is '.squareroot(81);
echo '<br>'.'Square root of 1 is '.squareroot(1);

Output:

Square Root in PHP

Conclusion

In this article, we learned what square root is, how do we calculate square roots with and without the built-in functions like sqrt(), pow(). What the sqrt() and pow() function does, how is it used in a program to find the square root? We learned about performing square root on numbers, floating-point numbers, negative numbers and so on. We also learned about calculating square root with user-defined input using form.

The above is the detailed content of Square Root in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software