0% found this document useful (0 votes)
17 views30 pages

Unit CHAP-2 ARREY

PHP arrays are versatile data structures that can store multiple values under a single name, allowing for efficient data management. There are three main types of arrays: indexed, associative, and multidimensional, each serving different purposes in web development. Key features include dynamic sizing, flexible indexing, and the ability to store heterogeneous elements, making arrays essential for handling complex data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views30 pages

Unit CHAP-2 ARREY

PHP arrays are versatile data structures that can store multiple values under a single name, allowing for efficient data management. There are three main types of arrays: indexed, associative, and multidimensional, each serving different purposes in web development. Key features include dynamic sizing, flexible indexing, and the ability to store heterogeneous elements, making arrays essential for handling complex data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT-2

CHAPTER-2
Introduction to PHP Arrays
In PHP, an array is a variable that can store multiple values under a single name. Arrays help manage
and manipulate large amounts of data efficiently. PHP arrays are flexible and can store different data
types, including integers, strings, objects, and even other arrays.

PHP provides three types of arrays:

1. Indexed Arrays – Arrays with numeric keys (starting from 0).

2. Associative Arrays – Arrays where keys are user-defined strings.

3. Multidimensional Arrays – Arrays containing other arrays as elements.

PHP arrays are widely used in web development for tasks such as storing form data, handling
database results, and processing JSON data. They are dynamically resizable, allowing elements to be
added or removed without predefined limits.

What is an Array in PHP?

An array in PHP is a collection of elements, each identified by an index (numeric or string-based key).
It provides a structured way to store and access multiple values within a single variable.

How to Create an Array in PHP

You can create an array using the array() function or the short [] syntax:

/ Indexed array

$fruits = array("Apple", "Banana", "Cherry");

$colors = ["Red", "Green", "Blue"];

// Associative array

$person = array("name" => "John", "age" => 30, "city" => "New York");
$student = ["id" => 101, "grade" => "A"];

// Multidimensional array

$students = array(

array("John", 25, "A"),

array("Alice", 22, "B"),

array("Bob", 24, "A")

);

Features of PHP Arrays

PHP arrays have several important features:

1. Heterogeneous Elements (Mixed Data Type)

PHP arrays can store a mix of different data types. You can store integers, strings, objects, or even
arrays in the same array.

$mixedArray = ["Hello", 100, 3.14, true, ["nested", "array"]];

2. Associative Arrays

PHP supports associative arrays, where each value is associated with a custom key (a string or
number). This is useful for creating key-value pairs.

$person = [

"name" => "Alice",

"age" => 28,

"email" => "[email protected]"

];

echo $person["name"]; // Output: Alice

3. Dynamic Sizing

PHP arrays do not require a fixed size declaration. You can add or remove elements dynamically.

$fruits = ["Apple", "Banana"];

$fruits[] = "Mango"; // Adding a new element

unset($fruits[1]); // Removing an element

4. Flexible Indexing

• Indexed arrays use numeric keys (starting at 0).

• Associative arrays allow custom string-based keys.


$indexedArray = ["A", "B", "C"];

$associativeArray = ["first" => "A", "second" => "B"];

5. Multidimensional Arrays

PHP allows arrays within arrays, enabling complex data structures.

$students = [

["John", 20, "Math"],

["Alice", 22, "Science"]

];

echo $students[0][0]; // Output: John

6. Loose Typing

PHP does not enforce strict data types for array elements, so an array can contain a mix of different
data types.

$myArray = ["Text", 123, 45.6, true];

PHP Arrays: A Detailed Explanation

Arrays in PHP are an essential data structure used to store multiple values in a single variable. They
allow for efficient storage and manipulation of data, making them crucial for handling large amounts
of information.

Types of PHP Arrays

PHP arrays are categorized into three primary types based on their indexing and structure:

1. Numerically Indexed Arrays

These arrays are the simplest form of PHP arrays. They use numeric keys to store and access
elements. PHP assigns numeric indices starting from 0.

Key Features of Numerically Indexed Arrays

1. Ordered Collection

o Elements are stored in a specific order and accessed based on their index.

2. Sequential Access

o Elements can be accessed sequentially using loops.

3. Zero-Based Indexing

o The first element has an index of 0, the second element has an index of 1, and so on.

4. Array Functions
o Useful functions include:

▪ count($array) – Returns the number of elements.

▪ array_push($array, $value) – Adds an element to the end.

▪ array_pop($array) – Removes the last element.

▪ array_slice($array, start, length) – Extracts a portion of the array.

5. Memory Efficiency

o Provides constant-time (O(1)) access to elements.

6. Flexible Data Types

o Can store integers, strings, objects, or even other arrays.

7. Array Iteration

o Can be iterated using for, foreach, or while loops.

Creating Numerically Indexed Arrays

There are two ways to create a numerically indexed array in PHP:

1. Using the array() function

The array() function is used to define an array with values.

Syntax:

$arrayName = array(value1, value2, value3, ...);

Example:

$fruits = array("Apple", "Banana", "Orange", "Mango");

2. Using Short Array Syntax []

Introduced in PHP 5.4, the [] syntax is a shorthand for defining arrays.

Syntax:

$arrayName = [value1, value2, value3, ...];

Example:

$fruits = ["Apple", "Banana", "Orange", "Mango"];

Accessing Elements in an Indexed Array

Elements are accessed using their numeric index. The first element has an index of 0.

Syntax:
$arrayName[index];

Example 1: Accessing Individual Elements

$fruits = ["Apple", "Banana", "Orange", "Mango"];

echo $fruits[0]; // Output: Apple

echo $fruits[2]; // Output: Orange

Explanation:

• $fruits[0] returns "Apple", as it is at index 0.

• $fruits[2] returns "Orange", which is at index 2.

Adding Elements to an Indexed Array

You can dynamically add elements to an array using [].

Example 2: Adding Elements

$colors = [];

$colors[] = "Red"; // Added at index 0

$colors[] = "Green"; // Added at index 1

echo $colors[0]; // Output: Red

Explanation:

• The empty array $colors = []; initializes an array.

• The values "Red" and "Green" are added sequentially.

• PHP automatically assigns numeric indices.

Iterating Through Indexed Arrays

You can iterate through an array using loops.

Example 3: Using a for Loop

$fruits = ["Apple", "Banana", "Orange", "Mango"];

for ($i = 0; $i < count($fruits); $i++) {

echo $fruits[$i] . "<br>";


}

Explanation:

1. The loop starts with $i = 0.

2. The condition $i < count($fruits) ensures the loop runs until all elements are printed.

3. $fruits[$i] accesses each element and prints it.

Output:

Apple

Banana

Orange

Mango

Numerically indexed arrays in PHP provide an efficient and straightforward way to manage ordered
collections of data. They support dynamic addition, modification, and iteration using built-in
functions and loops.

Key points:

• PHP arrays can store multiple values in one variable.

• Numerically indexed arrays have numeric keys starting from 0.

• Elements are accessed using [] notation.

• Arrays can be modified, expanded, and iterated using loops.

Associative Arrays in PHP

Introduction

An associative array in PHP is a type of array where each element is assigned a unique key, which
can be a string or an integer. Unlike numerically indexed arrays, which rely on numbers to access
elements, associative arrays use meaningful keys, making data retrieval more intuitive.

Why Use Associative Arrays?

Associative arrays are commonly used in PHP for:

• Storing key-value pairs (e.g., user data, product details).

• Making data more readable and meaningful (e.g., using name instead of [0]).

• Representing JSON-like structures in PHP.

• Handling structured data, such as database results.


Key Features of Associative Arrays

1. Key-Value Pair Structure

• Every element is represented as a key-value pair.

• Keys are unique within the array.

• Example:

$studentGrades = array(

"Alice" => 85,

"Bob" => 90,

"Charlie" => 78

);

o "Alice", "Bob", and "Charlie" are keys.

o 85, 90, and 78 are values.

2. Named Access

• Accessing values is more meaningful than using numeric indices.

• Example:

echo $studentGrades["Alice"]; // Output: 85

3. Flexible Key Types

• Keys can be strings or integers.

• Example:

$userInfo = array(

"ID" => 101,

"Name" => "John Doe",

"Age" => 30

);

4. PHP Array Functions

• PHP provides many functions to work with associative arrays:

o array_keys($array): Returns all keys.

o array_values($array): Returns all values.

o array_key_exists($key, $array): Checks if a key exists.

o isset($array[$key]): Checks if a key exists and is not null.

5. Iteration Using Loops


• Associative arrays can be iterated using foreach loops.

• Example:

foreach ($studentGrades as $name => $grade) {

echo "$name: $grade <br>";

Output:

Alice: 85

Bob: 90

Charlie: 78

Creating Associative Arrays

There are two ways to create an associative array:

1. Using the array() Function

$person = array(

"name" => "John",

"age" => 25,

"city" => "New York"

);

2. Using Short Array Syntax ([])

$person = [

"name" => "John",

"age" => 25,

"city" => "New York"

];

Accessing Elements in Associative Arrays

You can access elements using their keys.

Example: Accessing Values

$employee = [

"name" => "Jane Doe",

"position" => "Software Engineer",


"salary" => 60000

];

echo $employee["name"]; // Output: Jane Doe

echo $employee["salary"]; // Output: 60000

Example: Checking if a Key Exists

if (array_key_exists("position", $employee)) {

echo "Position: " . $employee["position"];

} else {

echo "Key does not exist!";

Modifying Elements in an Associative Array

You can update values by assigning a new value to an existing key.

Example: Modifying Values

$employee["salary"] = 65000;

echo $employee["salary"]; // Output: 65000

Example: Adding New Elements

$employee["department"] = "IT";

print_r($employee);

Output:

Array ( [name] => Jane Doe [position] => Software Engineer [salary] => 65000 [department] => IT )

Iterating Through Associative Arrays

1. Using foreach Loop

$studentGrades = [

"Alice" => 85,

"Bob" => 90,

"Charlie" => 78

];
foreach ($studentGrades as $name => $grade) {

echo "$name scored $grade <br>";

Nested Associative Arrays

PHP supports nested associative arrays, useful for storing structured data.

Example: Storing Product Information

$books = [

"book1" => [

"name" => "Artificial Intelligence",

"price" => 300,

"description" => "AI Concepts and Applications"

],

"book2" => [

"name" => "Web Programming",

"price" => 350,

"description" => "Web Development Using PHP"

],

"book3" => [

"name" => "Data Mining",

"price" => 250,

"description" => "Data Mining Techniques"

];

// Accessing a specific book's price

echo $books["book2"]["price"]; // Output: 350

Iterating Through Nested Arrays

foreach ($books as $key => $book) {

echo "Book: " . $book["name"] . "<br>";

echo "Price: " . $book["price"] . "<br>";

echo "Description: " . $book["description"] . "<br><br>";


}

Output:

Book: Artificial Intelligence

Price: 300

Description: AI Concepts and Applications

Book: Web Programming

Price: 350

Description: Web Development Using PHP

Book: Data Mining

Price: 250

Description: Data Mining Techniques

Why Use Associative Arrays?

• Better readability ("name" instead of [0]).

• Easy data access using meaningful keys.

• Supports structured and nested data.

• Many built-in functions for manipulation.

When to Use Associative Arrays?

• When keys are meaningful (e.g., "username", "email").

• When working with structured data (e.g., JSON-like objects).

• When representing database records.

The foreach Loop in PHP

The foreach loop is a control structure in PHP that simplifies iterating over arrays and objects. Unlike
the for or while loops, foreach is specifically designed for collections, eliminating the need for
manual index management.

Syntax

The foreach loop has two common syntaxes:

1. Iterating over an array’s values:

foreach ($array as $value) {


// Code to execute for each element

o $array is the array or object being iterated.

o $value takes the value of the current element in each iteration.

2. Iterating over an associative array (key-value pairs):

foreach ($array as $key => $value) {

// Code to execute for each key-value pair

o $key stores the key or index of the current element.

o $value stores the corresponding value.

Example 1: Iterating Over a Numeric Array

<?php

$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as $number) {

echo $number . "<br>";

?>

Output

Explanation

• The array $numbers contains five elements.

• The foreach loop iterates through each element.

• $number holds the current element's value in each iteration and is printed.

Example 2: Iterating Over an Associative Array


<?php

$ages = ["Swati" => 23, "Srikanth" => 40, "Lakshmi" => 35];

foreach ($ages as $name => $age) {

echo "$name is $age years old.<br>";

?>

Output

Swati is 23 years old.

Srikanth is 40 years old.

Lakshmi is 35 years old.

Explanation

• The associative array $ages stores names as keys and ages as values.

• $name holds the key (person's name), and $age holds the corresponding value (age).

• The values are printed using string interpolation.

Common Mistakes in foreach

1. Missing Concatenation or Incorrect Syntax in echo:

o Incorrect:

echo $name," is" $age. years old.<br>";

o Correct:

echo "$name is $age years old.<br>";

2. Using foreach on Non-Array Variables:

o Ensure that the variable being iterated is an array or an object.

Key Advantages of foreach

• Simplicity: No need for manual indexing ($i counters).

• Readability: Code is cleaner and more expressive.

• Automatic Iteration: Works on arrays of any size without needing count().

Multidimensional Arrays in PHP


A multidimensional array in PHP is an array that contains one or more arrays as its elements. Each
element in a multidimensional array can itself be an array, and the depth of these arrays can
theoretically extend infinitely. These arrays are particularly useful for representing complex data
structures such as tables, matrices, or hierarchical relationships.

Why Use Multidimensional Arrays?

Multidimensional arrays are used to store and organize data in a tabular format, where data is
arranged in rows and columns. They are particularly useful in:

• Storing database records in PHP.

• Representing a matrix (a grid-like structure).

• Creating hierarchical structures, such as organizational trees or category lists.

Syntax for Creating a Multidimensional Array

PHP provides two ways to define arrays:

1. Using the array() function

2. Using the short [] syntax

Syntax

$arrayName = array(

array(element1, element2, ...),

array(element1, element2, ...)

);

// OR using shorthand

$arrayName = [

[element1, element2, ...],

[element1, element2, ...]

];

• The outer array contains one or more inner arrays.

• Each inner array can contain different elements, including numbers, strings, or even other
arrays.

Example 1: Creating a Multidimensional Array

Student Information (Associative Array)

<?php
$students = array(

array("name" => "Swati", "age" => 25),

array("name" => "Snigdha", "age" => 20),

array("name" => "Srikanth", "age" => 45)

);

// Accessing elements

echo $students[0]["name"]; // Outputs: Swati

echo "<br>";

echo $students[1]["age"]; // Outputs: 20

?>

Explanation

• $students is a multidimensional associative array.

• Each element is itself an associative array with "name" and "age" keys.

• We access the elements using their index and key, like $students[0]["name"].

Example 2: Numeric (Indexed) Multidimensional Array

<?php

$matrix = array(

array(1, 2, 3),

array(4, 5, 6),

array(7, 8, 9)

);

echo $matrix[1][1]; // Outputs: 5

?>

Explanation

• This is a 2D array (Matrix format).

• The first index selects the row (starting from 0).

• The second index selects the column (starting from 0).

• $matrix[1][1] accesses row 1, column 1, which holds the value 5.


Example 3: Associative Multidimensional Array

<?php

$users = array(

"SK" => array("name" => "Srikanth", "age" => 25),

"RK" => array("name" => "Rama Krishna", "age" => 22)

);

echo $users["RK"]["name"]; // Outputs: Rama Krishna

?>

Explanation

• $users is an associative multidimensional array.

• Each key "SK" and "RK" stores another associative array with "name" and "age".

• $users["RK"]["name"] retrieves the name "Rama Krishna".

Example 4: Three-Dimensional Array

<?php

$threeDArray = array(

array(

array("a", "b"),

array("c", "d")

),

array(

array("e", "f"),

array("g", "h")

);

echo $threeDArray[0][1][0]; // Outputs: c

?>

Explanation
• This is a 3D array with three levels.

• $threeDArray[0] selects the first 2D array.

• $threeDArray[0][1] selects the second row in the first 2D array.

• $threeDArray[0][1][0] selects the first element ("c") from the second row of the first 2D
array.

Example 5: Mixed Indexed and Associative Multidimensional Array

<?php

$departments = array(

"Software" => array("Rashmi", "BCA"),

"Marketing" => array("Praveen", "BBA")

);

echo $departments["Software"][0]; // Outputs: Rashmi

?>

Explanation

• The outer array uses associative keys ("Software", "Marketing").

• The inner array uses indexed values.

• $departments["Software"][0] fetches "Rashmi".

Iterating Over a Multidimensional Array

To loop through multidimensional arrays, we use nested foreach loops.

Example: Iterating Over an Associative Multidimensional Array

<?php

$students = array(

array("name" => "Swati", "age" => 25),

array("name" => "Snigdha", "age" => 20),

array("name" => "Srikanth", "age" => 45)

);

foreach ($students as $student) {


echo "Name: " . $student["name"] . ", Age: " . $student["age"] . "<br>";

?>

Output

Name: Swati, Age: 25

Name: Snigdha, Age: 20

Name: Srikanth, Age: 45

Key Takeaways

• A multidimensional array can have nested arrays within it.

• You can create them using either numeric (indexed) arrays or associative arrays.

• To access elements, use multiple indices ($array[row][column]).

• To iterate over them, use nested foreach loops.

PHP Array Functions: A Comprehensive Guide

PHP provides a powerful set of array functions that help in performing various operations such as
sorting, counting, merging, extracting, and more. These functions simplify array manipulation and
improve code efficiency.

1. Checking If a Variable Is an Array

Function: is_array()

• This function checks whether a given variable is an array.

• It returns true if the variable is an array, otherwise false.

Example

<?php

$var = [1, 2, 3];

echo is_array($var); // Output: 1 (true)

?>

Explanation

• The function is_array($var) checks if $var is an array and returns 1 (true).

2. Counting Elements in an Array

Function: count()

• Counts the total number of elements in an array.


Example

<?php

$arr = [1, 2, 3];

echo count($arr); // Output: 3

?>

Explanation

• count($arr) returns the number of elements in $arr, which is 3.

3. Sorting an Array

Function: sort()

• Sorts an array in ascending order.

Example

<?php

$arr = [3, 1, 2];

sort($arr);

print_r($arr);

?>

Output

Array ( [0] => 1 [1] => 2 [2] => 3 )

Explanation

• sort($arr) arranges the elements in ascending order.

4. Randomizing an Array

Function: shuffle()

• Randomizes the order of elements in an array.

Example

<?php

$arr = [1, 2, 3];

shuffle($arr);

print_r($arr);

?>
Output (randomized)

Array ( [0] => 3 [1] => 1 [2] => 2 )

Explanation

• shuffle($arr) randomly reorders the elements.

5. Splitting a String into an Array

Function: explode()

• Splits a string into an array based on a delimiter.

Example

<?php

$str = "one,two,three";

print_r(explode(",", $str));

?>

Output

Array ( [0] => one [1] => two [2] => three )

Explanation

• explode(",", $str) breaks the string into an array using , as the delimiter.

6. Extracting Variables from an Array

Function: extract()

• Extracts associative array values as variables.

Example

<?php

$arr = ["color" => "blue", "size" => "medium"];

extract($arr);

echo $color; // Output: blue

?>

Explanation

• The extract($arr) function creates $color = "blue" and $size = "medium".

7. Creating an Array from Variables


Function: compact()

• Converts multiple variables into an associative array.

Example

<?php

$color = "blue";

$size = "medium";

print_r(compact("color", "size"));

?>

Output

Array ( [color] => blue [size] => medium )

Explanation

• compact("color", "size") creates an array with keys color and size and assigns their values.

8. Resetting and Moving Array Pointers

Functions: reset() and end()

• reset() moves the pointer to the first element.

• end() moves the pointer to the last element.

Example

$arr = [1, 2, 3];

echo reset($arr); // Output: 1

echo end($arr); // Output: 3

?>

Explanation

• reset($arr) points to the first element (1).

• end($arr) points to the last element (3).

9. Adding and Removing Elements from an Array

Function: array_push()

• Adds one or more elements to the end of an array.

Example

<?php
$arr = [1, 2];

array_push($arr, 3, 40);

print_r($arr);

?>

Output

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 40 )

Explanation

• array_push($arr, 3, 40) appends 3 and 40 to the array.

Function: array_pop()

• Removes and returns the last element of an array.

Example

<?php

$arr = [1, 2, 3];

$last = array_pop($arr);

echo $last; // Output: 3

print_r($arr);

?>

Output

Array ( [0] => 1 [1] => 2 )

Explanation

• array_pop($arr) removes the last element (3) and returns it.

10. Merging Two or More Arrays

Function: array_merge()

• Combines multiple arrays into one.

Example

<?php

$arr1 = [1, 2];

$arr2 = ["a", "b"];


$merged = array_merge($arr1, $arr2);

print_r($merged);

?>

Output

Array ( [0] => 1 [1] => 2 [2] => a [3] => b )

Explanation

• array_merge($arr1, $arr2) joins $arr1 and $arr2.

11. Retrieving All Keys of an Array

Function: array_keys()

• Returns an array of all keys.

Example

<?php

$arr = ["a" => 1, "b" => 2, "c" => 3];

$keys = array_keys($arr);

print_r($keys);

?>

Output

Array ( [0] => a [1] => b [2] => c )

Explanation

• array_keys($arr) extracts all keys ("a", "b", "c").

12. Retrieving All Values of an Array

Function: array_values()

• Returns an array of all values.

Example

<?php

$arr = ["a" => 10, "b" => 20, "c" => 30];

$values = array_values($arr);

print_r($values);

?>
Output

Array ( [0] => 10 [1] => 20 [2] => 30 )

Explanation

• array_values($arr) extracts all values (10, 20, 30).

Conclusion

PHP provides a variety of array functions that help in efficient array manipulation. Some of the most
commonly used functions include:

• Checking if a variable is an array: is_array()

• Counting elements: count()

• Sorting an array: sort(), shuffle()

• Splitting and merging arrays: explode(), array_merge()

• Adding/removing elements: array_push(), array_pop()

• Extracting keys/values: array_keys(), array_values()

Using Array Functions in PHP

PHP provides several built-in functions to manipulate arrays efficiently. These functions help in
sorting, merging, counting, searching, and modifying arrays.

Commonly Used PHP Array Functions

Function Description

is_array($var) Checks if a variable is an array.

count($arr) Counts the number of elements in an array.

sort($arr) Sorts an array in ascending order.

shuffle($arr) Randomizes the elements of an array.

explode($delimiter, $string) Splits a string into an array.

extract($arr) Converts array keys into variable names.

compact($var1, $var2, …) Creates an array from existing variables.

reset($arr) Moves the pointer to the first element.

end($arr) Moves the pointer to the last element.

array_push($arr, $value1, …) Adds elements to the end of an array.

array_pop($arr) Removes and returns the last element.


Function Description

array_merge($arr1, $arr2) Merges two or more arrays.

array_keys($arr) Retrieves all the keys from an array.

array_values($arr) Retrieves all the values from an array.

Example: Sorting an Array

<?php

$fruits = array("Orange", "Apple", "Banana", "Grape", "Cherry");

sort($fruits);

echo "<p>Sorted Array:</p>";

echo "<ul>";

foreach ($fruits as $fruit) {

echo "<li>$fruit</li>";

echo "</ul>";

?>

Output:

• Apple

• Banana

• Cherry

• Grape

• Orange

Explanation:

1. The $fruits array is created.

2. The sort($fruits) function arranges the elements in ascending order.

3. The sorted elements are displayed in an unordered list using a foreach loop.

2. Including and Requiring Files in PHP

PHP provides include() and require() functions to reuse code by importing external PHP files.

2.1 include() Function


• Includes the specified file in the script.

• If the file is missing, it issues a warning but allows the script to continue.

Syntax:

include 'filename.php';

Example: Using include() for Modularization

// header.php

<header>

<h1>Welcome to My Website</h1>

</header>

// footer.php

<footer>

<p>&copy; 2024 My Website. All rights reserved.</p>

</footer>

// main.php

<?php

include 'header.php';

echo "<section>";

echo "<h2>Main Content</h2>";

echo "<p>This is the main content of the page.</p>";

echo "</section>";

include 'footer.php';

?>

Explanation:

1. header.php contains the page header.

2. footer.php contains the footer section.

3. main.php includes header.php and footer.php to construct the webpage dynamically.


2.2 require() Function

• Works like include(), but if the file is missing, it causes a fatal error and stops script
execution.

• Use require() when the included file is essential.

Syntax:

require 'filename.php';

Example: Using require() for Database Configuration

<?php

require 'config.php'; // If config.php is missing, the script stops.

echo "Database connection established.";

require 'functions.php'; // Including additional functions

?>

Key Differences Between include() and require()

Function Error Type Script Execution if File is Missing

include() Warning Continues execution

require() Fatal error Stops execution

3. Variable Typing (Dynamic Type Casting in PHP)

PHP is a loosely typed language, meaning variables can change their data type automatically based
on usage.

3.1 Implicit Type Conversion (Type Juggling)

PHP automatically converts data types when needed.

Example: Implicit Conversion

<?php

$num = 10; // Integer

$result = $num * 3.14; // PHP converts $num to float

echo $result; // Output: 31.4

?>

Explanation:

• $num starts as an integer.


• When multiplied by 3.14 (a float), PHP converts $num to float for accurate calculation.

3.2 Dynamic Typing

Variables in PHP can change their type dynamically.

Example: Dynamic Typing

<?php

$value = 10; // Integer

$value = "Hello"; // Now, it's a string

echo $value; // Output: Hello

?>

Explanation:

• $value is first an integer.

• Later, it’s assigned a string, and PHP allows this change dynamically.

3.3 Explicit Type Casting

PHP allows manual type conversion using type casting operators.

Syntax:

$var = (type) $value;

Example: Explicit Type Casting

<?php

$floatValue = 10.5;

$intValue = (int) $floatValue; // Converts to integer

echo $intValue; // Output: 10

?>

Explanation:

• $floatValue is originally a float (10.5).

• Using (int), it’s explicitly converted to an integer (10).

4. Practical Examples of Array Operations

4.1 Sorting an Array (Program 1)

<!DOCTYPE html>
<html>

<head>

<title>Array Sorting</title>

</head>

<body>

<?php

$fruits = array("Orange", "Apple", "Banana", "Grape", "Cherry");

sort($fruits);

echo "<p>Sorted Array:</p>";

echo "<ul>";

foreach ($fruits as $fruit) {

echo "<li>$fruit</li>";

echo "</ul>";

?>

</body>

</html>

Output:

• Apple

• Banana

• Cherry

• Grape

• Orange

4.2 Sum of Array Elements (Program 2)

<!DOCTYPE html>

<html>

<head>

<title>Sum of Array Elements</title>

</head>
<body>

<?php

$numbers = array(10, 20, 30, 40, 50);

$sum = array_sum($numbers);

echo "<p>The sum of array elements is: $sum</p>";

?>

</body>

</html>

Output:

The sum of array elements is: 150

Explanation:

1. The $numbers array contains integer values.

2. array_sum($numbers) calculates the sum of the elements.

3. The total sum is displayed.

You might also like