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 TestsStart 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:
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:
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:
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:
Output – 2: With 100 as input.
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:
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!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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
