0% found this document useful (0 votes)
28 views

PHP If, Else, Else If

The document covers various PHP topics including conditional statements, loops, data types, forms, and logical operators. It includes code examples demonstrating PHP syntax and how to handle forms, validate input, and use logical operators.

Uploaded by

Vip Muneeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

PHP If, Else, Else If

The document covers various PHP topics including conditional statements, loops, data types, forms, and logical operators. It includes code examples demonstrating PHP syntax and how to handle forms, validate input, and use logical operators.

Uploaded by

Vip Muneeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

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>";

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

</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>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</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.

Here's a brief introduction to PHP:

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;
}
?>

<h2>PHP Form Validation Example</h2>


<form method="post" action="<?php echo htmlspecialchars
($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?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:

1. Logical AND (&&):


 The logical AND operator ( &&) returns true if both of the conditions it
connects are true.
 If any one of the conditions is false, the result will be false.
phpCopy code
$x = 5 ; $y = 10 ; if ( $x == 5 && $y == 10 ) { echo "Both conditions are true." ; } else { echo "At least one
condition is false." ; }
2. Logical OR (||):
 The logical OR operator ( ||) returns true if at least one of the
conditions it connects is true.
 If all conditions are false, the result will be false.
phpCopy code
$age = 25 ; if ( $age < 18 || $age >= 65 ) { echo "You are either under 18 or 65 and older." ; } else { echo
"You are between 18 and 64 years old." ; }
3. Combining Logical Operators: You can also combine these operators to
create more complex conditions:
phpCopy code
$a = true ; $b = false ; $c = true ; if (( $a && $b ) || $c ) { echo "Condition is true." ; } else { echo "Condition
is false." ; }

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:

1. Logical AND (&&):


 The logical AND operator ( &&) returns true if both of the conditions it
connects are true.
 If any one of the conditions is false, the result will be false.
phpCopy code
$x = 5 ; $y = 10 ; if ( $x == 5 && $y == 10 ) { echo "Both conditions are true." ; } else { echo "At least one
condition is false." ; }
2. Logical OR (||):
 The logical OR operator ( ||) returns true if at least one of the
conditions it connects is true.
 If all conditions are false, the result will be false.
phpCopy code
$age = 25 ; if ( $age < 18 || $age >= 65 ) { echo "You are either under 18 or 65 and older." ; } else { echo
"You are between 18 and 64 years old." ; }
3. Combining Logical Operators: You can also combine these operators to
create more complex conditions:
phpCopy code
$a = true ; $b = false ; $c = true ; if (( $a && $b ) || $c ) { echo "Condition is true." ; } else { echo "Condition
is false." ; }

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;
}
}

$goodbye = new Goodbye();


$goodbye->byebye();
?>

</body>
</html>
OPERATORS
PHP Operators
Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

PHP Arithmetic Operators


The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y


% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y't


power

PHP Assignment Operators


The PHP assignment operators are used with numeric values to write a value to
a variable.

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.

Assignment Same as... Description

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

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or
string):

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are o
same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y


!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are
the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than $x >= $y Returns true if $x is greater than or equal to $y


or equal to

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

<=> 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.

PHP Increment / Decrement Operators


The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Name Description


++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

And And $x and $y True if both $x and $y are true

Or Or $x or $y True if either $x or $y is true

Xor Xor $x xor $y True if either $x or $y is true, bu


both

&& And $x && $y True if both $x and $y are true


|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

PHP String Operators


PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1


$txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1


assignment

PHP Array Operators


The PHP array operators are used to compare arrays.

Operator Name Example Result


+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same key/


pairs

=== Identity $x === $y Returns true if $x and $y have the same key/
pairs in the same order and of the same type

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP Conditional Assignment Operators


The PHP conditional assignment operators are used to set a value depending on
conditions:

Operator Name Example Result


?: Ternary $x Returns the value of $x.
= expr1 ? expr2 : expr3 The value of $x is expr2 if expr
TRUE.
The value of $x is expr3 if expr
FALSE

?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.


The value of $x is expr1 if expr
and is not NULL.
If expr1 does not exist, or is NU
value of $x is expr2.
Introduced in PHP 7

IF STATEMENT
<!DOCTYPE html>
<html>
<body>

<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>

</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:

1. We start by initializing a variable $num with the value 1.


2. The while loop checks the condition $num <= 10. As long as this condition is
true, the code inside the loop will be executed.
3. Inside the loop, we print the value of $num along with some text.
4. We increment $num by 1 using $num++ to ensure that the loop progresses
towards its termination.

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="text"], select, input[type="submit"] {


margin: 5px;
padding: 5px;
width: 100%;
}

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.";
}

echo "Result: $result";


}
?>
</div>
</body>
</html>
PRIM NUMBER
<?php

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;
}

function printPrimesInRange($start, $end)


{
for ($i = $start; $i <= $end; $i++) {
if (isPrime($i)) {
echo $i . " ";
}
}
}

$start = 1; // Starting number


$end = 50; // Ending number

echo "Prime numbers between $start and $end are: ";


printPrimesInRange($start, $end);
?>
PHP FUNCTIONS
Defining a Function: You can define a function using the function keyword, followed by the
function name, a pair of parentheses for parameters (if any), and a block of code enclosed in
curly braces. Here's the basic syntax:
function functionName(parameter1, parameter2, ...) {
// Code to be executed
return result; // Optional
}

 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:

$result = functionName(argument1, argument2, ...);

 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:

function addNumbers($num1, $num2) {


$sum = $num1 + $num2;
return $sum;
}

$result = addNumbers(5, 7);


echo "The sum is: " . $result;

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;
}

$result = add(5, 3);


1. echo "The sum is: $result"; // Output: The sum is: 8

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:

1. sort() and rsort():


 sort() sorts an array in ascending order.
 rsort() sorts an array in descending order.
2. $numbers = array(5, 3, 9, 1, 6);
3. sort($numbers); // Sort in ascending order
4. // rsort($numbers); // Sort in descending order
5. print_r($numbers);

asort() and arsort():


 asort() sorts an associative array by values in ascending order while maintaining
the association between keys and values.
 arsort() sorts an associative array by values in descending order while
maintaining the association between keys and values.
$fruits = array("apple" => 2, "banana" => 4, "cherry" => 1);
asort($fruits); // Sort by values in ascending order
// arsort($fruits); // Sort by values in descending order
1. print_r($fruits);

ksort() and krsort():


 ksort() sorts an associative array by keys in ascending order.
 krsort() sorts an associative array by keys in descending order.
$months = array("January" => 1, "February" => 2, "March" => 3);
ksort($months); // Sort by keys in ascending order
// krsort($months); // Sort by keys in descending order
1. print_r($months);
2. Custom Sorting: You can also implement custom sorting using the usort() function,
where you define your own comparison function to sort the array based on your criteria.
$products = array(
array("name" => "Apple", "price" => 1.99),
array("name" => "Banana", "price" => 0.99),
array("name" => "Cherry", "price" => 2.49)
);

function sortByPrice($a, $b) {


return $a["price"] - $b["price"];
}

usort($products, "sortByPrice"); // Sort by price


1. print_r($products);
2. These sorting functions allow you to rearrange arrays in various ways to
meet your specific needs. Depending on your requirements, you can
choose the appropriate sorting function and the sorting order
(ascending or descending) that suits your application.

You might also like