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

Unit 2

The document provides a comprehensive overview of arrays in PHP, covering their creation, types (indexed, associative, and multidimensional), and manipulation techniques such as adding, removing, sorting, and searching elements. It also explains the use of include() and require() for file inclusion, highlighting their differences in error handling. Additionally, the document discusses implicit and explicit casting in PHP, detailing how variables can be converted between data types.

Uploaded by

darshunaik299
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)
9 views

Unit 2

The document provides a comprehensive overview of arrays in PHP, covering their creation, types (indexed, associative, and multidimensional), and manipulation techniques such as adding, removing, sorting, and searching elements. It also explains the use of include() and require() for file inclusion, highlighting their differences in error handling. Additionally, the document discusses implicit and explicit casting in PHP, detailing how variables can be converted between data types.

Uploaded by

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

ARRAYS in PHP

UNIT 2
Array: Creating Arrays
• An array stores multiple values in one single variable.
• To create an array is using the array() function. It takes any number of
comma-separated values as arguments.
• These values can be of any data type, including strings, integers, floats,
booleans, or even other arrays.
Example
• $fruits = array("apple", "banana", "orange");

Example
• $mixed_array = array(10, "hello", 3.14, true);
• We can use a shorter syntax for creating arrays using square brackets [].
Example

• $colors = ["red", "green", "blue"];


Accessing Array elements
• To access an array item, we can refer to the index number for indexed
arrays, and the key name for associative arrays.
Example:
• $fruits = array("apple", "banana", "orange");
• $first_fruit = $fruits[0]; // $first_fruit will contain "apple"
• $last_fruit = $fruits[2]; // $last_fruit will contain "orange

• We could also use curly braces to access array elements


Example:
• $fruits = array("apple", "banana", "orange");
• $first_fruit = $fruits{"0"}; // $first_fruit will contain "apple"
Types of Arrays:
1. Indexed array
• In indexed arrays each item has an index number.
• By default, the first item has index 0, the second item has item 1, etc

Example:
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
?>
</body>
</html>
2. Associative arrays
• Associative arrays are arrays that use named keys.
Example:
$student_ages = [ "Alice" => 20, "Bob" => 25, "Charlie" => 18 ];
$alices_age = $student_ages["Alice"];
echo $student_ages [“Bob”]

Change the value in associative array

$student_ages = [ "Alice" => 20, "Bob" => 25, "Charlie" => 18 ];


$student_ages[“Alice”]=34;
Indexed v/s Associative arrays
3.Multidimensional arrays
Arrays can hold other arrays, creating multidimensional structures.
This is useful for representing complex data hierarchies

$students = array(
array(
"name" => "Alice",
"age" => 20,
"grades" => array(85, 90, 78)
),
array(
"name" => "Bob",
"age" => 22,
"grades" => array(75, 88, 92)
)
);

Accessing Elements:
$alices_second_grade = $students[0]["grades"][1]; // $alices_second_grade will contain 90
Manipulating Arrays
• PHP offers a rich set of functions and techniques to manipulate arrays,
allowing to modify, add, remove and reorganize their elements.

1. Adding Elements:
Appending: Use the array_push() function to add elements to the end
of the array.
Prepending: Use the array_unshift() function to add elements to the
beginning of the array.
Inserting at specific index: Use array_splice() to insert elements at a
specific index
Example : array_push()
$fruits = ["apple", "banana"];
array_push($fruits, "orange"); // Append "orange"

Example : array_unshift()
$fruits = ["apple", "banana"];
array_unshift($fruits, "mango"); // Prepend "mango"

Example : array_splice
$fruits = ["apple", "banana"];
array_splice($fruits, 2, 0, "kiwi"); // Insert "kiwi" at index 2
echo “new array is”
print_r($fruits);

// Output: Array ( [0] => mango [1] => apple [2] => kiwi [3] => banana [4] =>
orange )
2.Removing Elements:
• Removing the first element: Use array_shift() to remove the element
from the beginning of the array.
Example:
$first_fruit = array_shift($fruits); // Remove the first element
print_r($fruits);

• Removing the last element: Use array_pop() to remove the element


from the end of the array.
Example:
$num=array(1,2,3);
$last_num=array_pop($num);
echo $last_num;
• Removing by index: Use array_splice() directly to remove elements
based on their index and number of elements to remove.
Example:
$num=array(1,2,3);
$rem_element=array_splice($num,1,2);
echo “removed elements are”;
print_r($rem_element);
3. Sorting and Reorganizing:

• sort(): Sorts elements in ascending order by default.


• rsort(): Sorts elements in descending order by default.
• asort(): Sorts elements based on values in ascending order.
• arsort(): Sorts elements based on values in descending order.
• ksort(): Sorts elements based on keys in ascending order.
• krsort(): Sorts elements based on keys in descending order
$numbers = [3, 1, 4, 5, 2];

// Sort in ascending order


sort($numbers);

// Sort associative array by value (ascending)


$ages = ["Alice" => 25, "Bob" => 20, "Charlie" => 30];
asort($ages);

print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
print_r($ages); // Output: Array ( [Bob] => 20 [Alice] => 25 [Charlie] => 30 )
4. Searching:
• array_search(): Finds the index of the first occurrence of a value.
Example:
$num=array(1,2,3);
$key=array_search(3,$num);
echo $key

• in_array(): Checks if a value exists in the array and returns true if found.
Example:
$num=array(1,2,3);
$a=in_array(4,$num);
echo $a ? ‘found’ : ‘not found’;
Displaying array
1. Using print_r():
• The print_r() function is a versatile tool for displaying the contents of an array,
including its structure, keys (for associative arrays), and values.
• It presents the information in a human-readable format, making it useful for
debugging and inspecting the contents of your arrays.
Example:
$fruits = ["apple", "banana", "orange"];
$student_ages = ["Alice" => 20, "Bob" => 25];
print_r($fruits); // Output: Array ( [0] => apple [1] => banana [2] => orange )
print_r($student_ages);
// Output: Array ( [Alice] => 20 [Bob] => 25 )
2. Using var_dump():

• Similar to print_r(), var_dump() displays information about a variable.


• It provides a more detailed output, including the data type and size of
the array, along with its elements.

Example:
$fruits = ["apple", "banana", "orange"];

var_dump($fruits);
//Output: array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=>
string(6) "orange" }
Array Functions in php
• Array functions are essential tools in PHP for working with and
manipulating arrays.
• They offer a wide range of capabilities to manage, search, sort,
modify, and interact
Including and Requiring Files- use of Include() and Require()
• Including files is very useful when we want to include the same PHP,
HTML or text on multiple pages of a website
• In PHP, include and require are used to insert the content of one PHP
file into another.

Functionality:
• Both include and require achieve the same basic task:
They locate the specified file (filename).
They parse the contents of that file as PHP code.
They insert the parsed code into the current script at the point where
the include or require statement is used.
Key Difference:
• The crucial distinction between include and require lies in how they handle errors
during file inclusion:

include:
• If the file (filename) is not found, a warning (E_WARNING) is generated, but the
script continues execution. T
• Use include() when the included file's presence is not critical for the script to
functionight lead to unexpected behavior if the included file is essential for the script
to function properly.
require:
• If the file (filename) is not found, a fatal error (E_COMPILE_ERROR) is generated, and
the script halts execution
• Use require() when the included file is essential for the script to work properly.

• . This en
• sures that the script doesn't proceed without the necessary code from the included
file.
• Example for include(): header.php:
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>My Website</h1>
<nav>
<a href="index.php">Home</a>
<a href="about.php">About</a>
<a href="contact.php">Contact</a>
</nav>
</body>
</html>
Example: index.php:

<?php
include "header.php"; // Include the header file
?>

<p>This is the content of the index page.</p>

<?php
include "footer.php"; // Include the footer file (assuming it exists)
?>
• In the above code, The index.php file includes header.php using
include().
• The content of header.php is inserted at the point of inclusion.
• The HTML structure, title, and navigation menu from header.php are
now part of index.php.
• if it is not able to find another file(footer.php )to include then it gives
a warning and executes after code
Example for require()
<html>

<body>
<h2>This is the content of index.php file.</h2>

<?php
require(“header.php");
?>
<h2>This is content after including another_file content</h2>

</body>
</html>

In this, we use require but if it is not able to find another file to include then it gives a fatal
error and does not execute after code
Implicit and Explicit Casting in PHP
• In PHP, casting refers to the process of converting a variable from one data type to
another.
• There are two ways: implicit casting and explicit casting.
Implicit casting (Automatic Type Coercion):
• PHP automatically converts a variable's data type during operations or assignments when
necessary.
• This can be convenient, but it can also lead to unexpected results if not understood
properly.
Examples of Implicit Casting:
i. Numeric Conversions: When a string containing only numbers is used in a numeric
context (like arithmetic operations or comparisons), PHP converts it to a number.
Example:
<?php
$str_num = "10";
$sum = $str_num + 5; // $sum will be 15 (integer)
echo $sum
?>
ii.Boolean Conversions: PHP treats empty strings (null) and false as equllent to
booleen false. Any other value is considered true.

Example:
<?php
$empty_str = "";
if ($empty_str) {
print(“empty string evaluates to false”);
}else
print(“empty string evaluates to true”);
}
?>
2. Explicit Casting (Type Juggling):
• Explicitly instruct PHP to convert a variable to a specific data type using
casting operators.
• This provides more control over data type conversions and reduces the
risk of unexpected behavior.
Common Casting Operators:
• (int): Converts to integer.
• (float): Converts to float (decimal number).
• (string): Converts to string.
• (bool): Converts to boolean (true or false).
• (array): Converts to array.
Example:
<?php
$numStr=“10.5”;
$intVal=(int) $numStr;
?>

You might also like