PHP If, Else, Else If
PHP If, Else, Else If
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
</body>
</html>
FOR LOOP
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
DATA TYPES
1. Integer (int): Integers are whole numbers without a decimal point.
phpCopy code
$number = 42 ;
2. Float (float): Floats, also known as floating-point numbers, are numbers with a decimal
point.
phpCopy code
$pi = 3.14159 ;
3. String (string): Strings are sequences of characters enclosed in single or double quotes.
phpCopy code
$name = "John" ;
4. Boolean (bool): Booleans represent true or false values.
phpCopy code
$isTrue = true ; $isFalse = false ;
5. Array: Arrays can store multiple values in an ordered or associative manner.
phpCopy code
$fruits = array ( "apple" , "banana" , "cherry" ); $person = array ( "name" => "John" , "age" => 30 );
6. Object: Objects are instances of user-defined classes that can have properties and
methods.
phpCopy code
class Car { public $brand ; public $model ; } $myCar = new Car (); $myCar ->brand = "Toyota" ; $myCar -
>model = "Camry" ;
7. NULL: NULL represents a variable with no value.
phpCopy code
$emptyValue = null ;
8. Resource: Resources are special variables that hold references to external resources like
database connections or file handles. They are typically created and managed by PHP
extensions.
phpCopy code
$file = fopen ( "example.txt" , "r" );
Here's a simple PHP script that demonstrates the use of different data types:
phpCopy code
<?php $number = 42 ; $pi = 3.14159 ; $name = "John" ; $isTrue = true ; $isFalse = false ; $fruits =
array ( "apple" , "banana" , "cherry" ); $person = array ( "name" => "John" , "age" => 30 ); class Car { public
$brand ; public $model ; } $myCar = new Car (); $myCar ->brand = "Toyota" ; $myCar ->model = "Camry" ;
$emptyValue = null ; echo "Number: " . $number . "<br>" ; echo "Pi: " . $pi . "<br>" ; echo "Name: " .
$name . "<br>" ; echo "Is True: " . $isTrue . "<br>" ; echo "Is False: " . $isFalse . "<br>" ; echo "Fruits: " .
implode ( ", " , $fruits ) . "<br>" ; echo "Person: " . $person [ "name" ] . " (Age: " . $person [ "age" ] . ")<br>" ;
echo "Car: " . $myCar ->brand . " " . $myCar ->model . "<br>" ; echo "Empty Value: " . $emptyValue .
"<br>" ; ?>
PHP-FORM HANDING
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
INTRODUCTION TO PHP
PHP, which stands for "Hypertext Preprocessor," is a widely-used open-source server-
side scripting language designed for web development. It is embedded within HTML
code and executed on the server, generating dynamic content that is then sent to the
client's web browser. PHP is known for its simplicity, versatility, and extensive
community support, making it one of the most popular languages for building web
applications.
1. History: PHP was created by Rasmus Lerdorf in 1994 as a set of Common Gateway
Interface (CGI) binaries to track web visits. Over time, it evolved into a scripting
language, and PHP 3 was released in 1998, making it more accessible for web
development. Subsequent versions added powerful features and improved performance.
2. Server-Side Scripting: PHP is primarily used on the server side of web development.
When a client requests a web page, the PHP code on the server processes the request,
interacts with databases, and generates HTML or other content dynamically. This
dynamic nature makes it suitable for creating interactive and data-driven websites.
3. Syntax: PHP code is embedded directly within HTML files using special tags. These tags
are typically enclosed within <?php and ?> delimiters, allowing you to switch between
PHP and HTML seamlessly.
phpCopy code
<!DOCTYPE html> <html> <head> <title>PHP Example</title> </head> <body> <h1> <?php echo "Hello,
World!" ; ?> </h1> </body> </html>
4. Versatility: PHP is highly versatile and can be used for various purposes, including:
Building dynamic web pages and web applications.
Creating and managing databases (e.g., MySQL, PostgreSQL).
Handling form submissions and user authentication.
Generating dynamic content, such as charts, PDFs, and images.
Integrating with other web technologies like HTML, CSS, JavaScript, and various
web frameworks (e.g., Laravel, Symfony, CodeIgniter).
5. Community and Resources: PHP has a vast and active developer community. There are
numerous online resources, forums, and libraries available to help developers learn and
solve problems. Popular platforms like WordPress, Joomla, and Drupal are built on PHP.
6. Cross-Platform: PHP is cross-platform and can run on various web servers (e.g.,
Apache, Nginx) and operating systems (e.g., Linux, Windows, macOS).
7. Security Considerations: While PHP is powerful, it also requires careful handling to
prevent security vulnerabilities. Developers should be aware of common security pitfalls,
such as SQL injection and cross-site scripting (XSS), and follow best practices to secure
their PHP applications.
PHP –FORM VALIDATION
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
PHP VAIABLE TYPES
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
PHP STRINGS
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!");
?>
</body>
</html>
PHP GET AND POST METHOD
In PHP, the GET and POST methods are used to retrieve data sent from a web form or through a URL
query string. These methods allow you to collect user input and process it on the server. Here's an
explanation of both methods:
1. GET Method:
The GET method is used to request data from a specified resource.
It appends data to the URL in the form of query parameters.
It is suitable for sending small amounts of data.
Data is visible in the URL, making it less secure for sensitive information.
It is widely used for search queries and navigating web pages.
Example of using GET to pass data via a URL:
phpCopy code
// Assuming the URL looks like this: example.php?name=John&age=30 $name = $_GET [ 'name' ]; $age =
$_GET [ 'age' ]; echo "Name: " . $name . "<br>" ; echo "Age: " . $age . "<br>" ;
2. POST Method:
The POST method is used to send data to the server for processing.
Data is sent in the request body, not visible in the URL, which makes it more secure for
sensitive information.
It is suitable for sending larger amounts of data and is commonly used for form submissions,
such as login forms and data entry forms.
Example of using POST to collect data from a form submission:
phpCopy code
<!-- HTML form in example.html --> <form method= "post" action= "process.php" > <input type= "text"
name= "username" placeholder= "Username" > <input type= "password" name= "password"
placeholder= "Password" > <input type= "submit" value= "Login" > </form>
phpCopy code
// process.php $username = $_POST [ 'username' ]; $password = $_POST [ 'password' ]; // Process the data, e.g.,
authenticate the user // ... // Redirect or display a response to the user
LOGICAL AND OR
In PHP, you can use the logical AND ( &&) and logical OR (||) operators to
perform conditional logical operations in your code. These operators are often
used to evaluate multiple conditions and make decisions based on whether
those conditions are true or false.
Here's how you can use the logical AND and logical OR operators in PHP:
In the example above, the condition evaluates to true because the logical OR
operator (||) makes the entire condition true since $c is true, even though $a
&& $b is false.
These logical operators are essential for creating conditional statements and
controlling the flow of your PHP code based on various conditions. They are
widely used in decision-making processes, such as determining whether a user
has the required permissions, validating user input, and more.
ARRAYS AND FUNcTION
In PHP, you can use the logical AND ( &&) and logical OR (||) operators to
perform conditional logical operations in your code. These operators are often
used to evaluate multiple conditions and make decisions based on whether
those conditions are true or false.
Here's how you can use the logical AND and logical OR operators in PHP:
In the example above, the condition evaluates to true because the logical OR
operator (||) makes the entire condition true since $c is true, even though $a
&& $b is false.
These logical operators are essential for creating conditional statements and
controlling the flow of your PHP code based on various conditions. They are
widely used in decision-making processes, such as determining whether a user
has the required permissions, validating user input, and more.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
VARIABLE AND CONSTANT
<!DOCTYPE html>
<html>
<body>
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}
</body>
</html>
OPERATORS
PHP Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
The basic assignment operator in PHP is "=". It means that the left operand
gets set to the value of the assignment expression on the right.
x=y x=y The left operand gets set to the value of the expressio
the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
ADVERTISEMENT
=== Identical $x === $y Returns true if $x is equal to $y, and they are o
same type
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or great
zero, depending on if $x is less than, equal to,
greater than $y. Introduced in PHP 7.
=== Identity $x === $y Returns true if $x and $y have the same key/
pairs in the same order and of the same type
IF STATEMENT
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
</body>
</html>
SWITCH STATEMENT
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>
WHILE STSTEMENT
Here's another example of how to use a while statement in PHP. In this
example, we'll create a while loop to display numbers from 1 to 10:
phpCopy code
$num = 1 ; // Initialize the variable with the starting value while ( $num <= 10 ) { echo "Number: " . $num .
"<br>" ; $num ++; // Increment the variable by 1 in each iteration }
In this code:
When you run this code, it will display the numbers from 1 to 10 on the
screen:
makefileCopy code
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: 7 Number: 8 Number: 9
Number: 10
The while loop continues executing as long as the condition remains true. In
this case, it stops when $num becomes greater than 10.
NUMBER 17:
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="calculator">
<h2>Simple Calculator</h2>
<form action="calculator.php" method="post">
<input type="text" name="num1" placeholder="Enter first
number" required>
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="num2" placeholder="Enter second
number" required>
<input type="submit" value="Calculate">
</form>
</div>
</body>
</html>
.calculator {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
text-align: center;
background-color: #f5f5f5;
}
input[type="submit"] {
background-color: #007bff;
color: #fff;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #0056b3;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator Result</title>
</head>
<body>
<div class="calculator">
<h2>Simple Calculator</h2>
<?php
if (isset($_POST['num1'], $_POST['operator'], $_POST['num2'])) {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operator = $_POST['operator'];
$result = 0;
switch ($operator) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
if ($num2 != 0) {
$result = $num1 / $num2;
} else {
echo "Division by zero is not allowed.";
}
break;
default:
echo "Invalid operator.";
}
function isPrime($number)
{
if ($number <= 1) {
return false;
}
if ($number <= 3) {
return true;
}
if ($number % 2 == 0 || $number % 3 == 0) {
return false;
}
$i = 5;
while ($i * $i <= $number) {
if ($number % $i == 0 || $number % ($i + 2) == 0) {
return false;
}
$i += 6;
}
return true;
}
functionName: Replace this with the name you choose for your function.
parameter1, parameter2, ...: These are optional parameters that the function can
accept. You can have zero or more parameters.
return result;: If needed, you can use the return statement to send a value back
from the function. It's optional.
Calling a Function: To execute a function, you simply use its name followed by
parentheses. If the function accepts parameters, you pass them within the parentheses.
For example:
functionName: Replace this with the name of the function you want to call.
argument1, argument2, ...: These are the values you pass as arguments to the
function, corresponding to its parameters.
Example Function: Here's a simple example of a PHP function that calculates the sum
of two numbers:
In this example:
We define a function called addNumbers that accepts two parameters, $num1 and $num2.
Inside the function, we calculate the sum of the two numbers and return it.
We call the addNumbers function with arguments 5 and 7 and store the result in the
variable $result.
Finally, we display the result using echo.
This is a basic illustration of how functions work in PHP. You can create functions for a
wide range of tasks, from simple calculations to complex operations, and then reuse
them throughout your code for increased maintainability and readability.
HOW TO CALL PHP FUNCTIONS
Calling PHP functions is straightforward. Once you've defined a function, you can call it
by using its name followed by parentheses, and if the function expects any arguments
(parameters), you pass them within the parentheses. Here's a step-by-step guide on
how to call PHP functions:
1. Define a Function: First, you need to define a PHP function. You do this using the
function keyword followed by the function name, parameters (if any), and the
function's code block enclosed in curly braces. For example:
2. function greet($name) {
3. echo "Hello, $name!";
4. }
5. Call the Function: To call the function, simply use its name followed by parentheses. If
the function expects parameters, provide them within the parentheses. For example:
6. greet("John");
7. In this case, we are calling the greet function with the argument "John". The
function will be executed, and it will print "Hello, John!" to the screen.
8. Handling the Function's Return Value (Optional): If the function returns a
value (using the return statement), you can capture and use that value by
assigning it to a variable:
function add($a, $b) {
return $a + $b;
}
2. In this example, the add function returns the sum of its two parameters, and we
capture that result in the variable $result.
That's how you call PHP functions. The key points to remember are to use the function's
name followed by parentheses, and if it expects parameters, provide them in the correct
order. If the function returns a value, you can store it in a variable for further use.
3.
Php sorting array
PHP provides various functions for sorting arrays based on different criteria. The most
commonly used sorting functions in PHP include sort(), rsort(), asort(), arsort(),
ksort(), and krsort(). Here's an overview of these functions: