Professional Documents
Culture Documents
Chapter 2
Chapter 2
Chapter 2
o/p
brand: Ford
model: Mustang
year: 1964
<?php
$car = array(1=>"Ford", 5=>"Mustang", 10=>1964);
$car["year"] = 2024;
echo $car[5];
?>
Multidimensional Arrays
• These array contains nested arrays.
• Array elements are accessed using multiple indices
• Multidimensional array allow user to group related
data together
Syntax
array(
array(elements…), array(elements…),
array(elements…))
<?php
$student =array(
array(“name”=>”abc”,”rollno”=>”3”,”mobile”=>”8976
766323”),
array(“name”=>”xyz”,”rollno”=>”2”,”mobile”=>”5678
976323”),
array(“name”=>”abc”,”rollno”=>”4”,”mobile”=>”7663
238765”)
);
echo “name of rollno 2 is”.$student[1][“name”];
echo “mobile no of rollno 4 is”.$student[2]
[“mobile”];
?>
<?php
$mobile = array (
array(“samsung",22,18),
array(“Redmi",15,13),
array(“apple",5,2),
array(“oppo",17,15)
);
}
echo “</ul>”;
}
?>
Extracting Data From Arrays
• extract()
• The extract() function does array to variable conversion. That
is it converts array keys into variable names and array values
into variable value.
• list()
• It is used to assign array values to multiple variables at a
time.
This function will only work on numerical arrays. When the
array is assigned to multiple values, then the first element in
the array is assigned to the first variable, second to the second
variable, and so on, till the number of variables. The number of
variables cannot exceed the length of the numerical array.
Extract () function
• <?php
• // input array
• $state =array(“AS”=>"ASSAM", "OR"=>"ORRISA",
"KR"=>"KERELA");
• extract($state);
• // after using extract() function
• echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR"; ?>
Output
Array ( [studname] =>abc [mobile] => 986325687[age] => 41 )
Understanding implode() and explode() in PHP
• Syntax:
• array explode ( string $delimiter , string $string [, int
$limit = PHP_INT_MAX ] )
• Example:
• <?php
• $str = 'one,two,three,four';
• // zero limit
• print_r(explode(',',$str,0));
• print "<br>";
• // positive limit
• print_r(explode(',',$str,2));
• print "<br>";
• // negative limit
• print_r(explode(',',$str,-1));
• Array
?>
( [0] => one,two,three,four )
Array ( [0] => one [1] => two,three,four )
Array ( [0] => one [1] => two [2] => three )
array_flip()
• A PHP function for exchanging keys with their
associated values in an array.
• Creates a new array where keys become values,
and values become keys.
• array_flip ( array $array )
• $array: The input array to be flipped.
• Example:
• $input = array("apple" => "red", "orange" => "orange",
"banana" => "yellow");
• $output = array_flip($input);
• // Result:
• ["red" => "apple", "orange" => "orange", "yellow" =>
Traversing Arrays
The process of visiting each element in an array.
• Using foreach Loop
• foreach Loop:
– Simplifies array traversal.
– Iterates over each element in the array.
• Example:
• $colors = ["red", "green", "blue"];
• foreach ($colors as $color)
• {
• echo $color . "<br>";
• }
• Associative Arrays:
– Use foreach to iterate over key-value pairs.
• Example:
$person = ["name" => "John", "age" => 25, "city"
=> "New York"];
• foreach ($person as $key => $value)
• { echo "$key: $value <br>"; }
Using for Loop
• for Loop:
– Useful when you need the index of the current element.
• Example:
• $fruits = ["apple", "orange", "banana"];
• for ($i = 0; $i < count($fruits); $i++)
• { echo $fruits[$i] . "<br>"; }
Deleting Elements from Arrays in PHP
• Dynamic Data:
– Arrays often store dynamic data.
– Need to remove elements based on certain conditions or
requirements.
• array_values():
– A PHP function that returns all the values of an array.
– Re-indexes the array numerically.
• Syntax
• array array_values ( array $array )
• $array: The input array.
• Example:
• $colors = ["red" => "apple", "yellow" => "banana", "green"
=> "lime"]; $values = array_values($colors);
• Result of array_values()
• Numerically Indexed:
– The resulting array has numeric keys starting from 0.
• // Result: ["apple", "banana", "lime"]
The Need for Sorting
• Organizing Data:
– Arrays often contain data that needs to be organized.
– Sorting facilitates efficient data retrieval and presentation.
• Sorting Functions
• PHP's Array Sorting Functions
• sort():
– Sorts an array in ascending order.
• rsort():
– Sorts an array in descending order.
• asort():
– Sorts an associative array in ascending order, maintaining key-value pairs.
• arsort():
– Sorts an associative array in descending order, maintaining key-value pairs.
Numerical Sorting
• Using sort() and rsort()
• sort():
– Numerically sorts an array in ascending order.
• Example:
• $numbers = [4, 2, 8, 1, 6];
• sort($numbers); // Result: [1, 2, 4, 6, 8]
• rsort():
– Numerically sorts an array in descending order.
• Example:
• $numbers = [4, 2, 8, 1, 6]; rsort($numbers);
• // Result: [8, 6, 4, 2, 1]
Associative Sorting
• Using asort() and arsort()
• asort():
– Sorts an associative array in ascending order based on values.
• Example:
• $grades = ["John" => 85, "Jane" => 92, "Bob" => 78];
• asort($grades);
• Result: ["Bob" => 78, "John" => 85, "Jane" => 92]
• arsort():
– Sorts an associative array in descending order based on values.
• Example:
• $grades = ["John" => 85, "Jane" => 92, "Bob" => 78];
• arsort($grades);
• Result: ["Jane" => 92, "John" => 85, "Bob" => 78]
Key Sorting
• Using ksort() and krsort()
• ksort():
– Sorts an associative array in ascending order based on keys.
• Example:
• $fruits = ["banana" => "yellow", "apple" => "red", "orange" =>
"orange"];
• ksort($fruits);
• Result: ["apple" => "red", "banana" => "yellow", "orange" => "orange"]
• krsort():
– Sorts an associative array in descending order based on keys.
• Example:
• $fruits = ["banana" => "yellow", "apple" => "red", "orange" =>
"orange"];
• krsort($fruits);
• Result: ["orange" => "orange", "banana" => "yellow", "apple" => "red"]
Custom Sorting
• Using usort() for Custom Sorting
• usort():
– Allows for user-defined sorting based on a callback function.
• Example:
• $names = ["John", "Alice", "Bob", "Charlie"];
usort($names, function ($a, $b) { return strlen($a) -
strlen($b); });
• // Result: ["Bob", "John", "Alice", "Charlie"]
Splitting array
array_slice()
• it is used to fetch a part of an array by slicing through it, according to the users choice.
• Syntax:
• array_slice($array, $start_point, $slicing_range, preserve)
• $array (mandatory): This parameter refers to the original array, we want to slice.
• $start_point (mandatory): This parameter refers to the starting position of the array from where
the slicing need to be performed. It is mandatory to supply this value. If the value supplied is
negative, then the function starts slicing from the end of the array, i.e., -1 refers to the last
element of the array.
• $slicing _range (optional): This parameter refers to the range or limit point upto which the slicing
is needed to be done. A negative value will indicate the count from the end of the string. On
leaving blank the function will slice through all the values as mentioned in the starting point right
up to the end.
• preserve (optional): This parameter can take only two boolean parameters, i.e.,
either True or False. This will tell the function whether to preserve the keys or reset it. True refers
to preserve the keys and false refers to reset the keys. False being the default value.
• Return Value: As already mentioned this function will return the selected or the sliced parts of the
• <html>
• <body>
• <?php
• $a=array("red","green","blue","yellow","brown");
• print_r(array_slice($a,1,2));
• ?>
• </body>
• </html>
• Example 2
<?php
$car = array("Ford", "Honda", "Hyundai", "Toyota", "Volkswagen")
;
print_r(array_slice($car, 2, -1));
?>
• Output:
• Example 3
<?php
$car = array("Ford", "Honda", "Hyundai", "Toyota", "Volkswagen");
print_r(array_slice($car, 2, -1, true));
?>
• Output:
• Array ( [2] => Hyundai [3] => Toyota )
• Example 4
<?php
$subject = array('java','C++','os','DBMS');
$result= array_slice($subject,3);
print_r($result);
$result= array_slice($subject,-2,1);
print_r($result);
$result= array_slice($subject,0,4);
print_r($result);
?>
• Output:
• Array ( [0] => DBMS ) Array ( [0] =>os ) Array ( [0] => java [1] => C++ [2] =>os [3] => DBMS )
array_chunk()
• This function is an inbuilt function in PHP which is used to split an array into
parts or chunks of given size depending upon the parameters passed to the
function. The last chunk may contain fewer elements than the desired size of
the chunk.
• Syntax:
• array array_chunk( $array, $size, $preserve_keys )
• Parameters: This function accepts three parameters as shown in the above
syntax. The parameters are described below:
• $array: This parameter represents the array that is needed to be divided into
chunks.
• $size: This parameter is an integer which defines the size of the chunks to be
created.
• $preserve_keys: This parameter takes Boolean value. When this parameter is
set to TRUE then the keys are preserved, otherwise the chunk is reindexed
starting from 0.
• Return value: This function returns a multidimensional array indexed starting
from 0. Each chunk contains $size number of elements, except the last chunk
which may contain lesser number of elements.
• $input_array = array('a', 'b', 'c', 'd', 'e');
array_chunk($input_array, 2);
• Output : Array( [0] => Array ( [0] => a [1] => b ) [1]
=> Array ( [0] => c [1] => d ) [2] => Array ( [0] =>
e))
• Syntax:
• array array_keys($input_array, $search_value, $strict)Parameters: The function
takes three parameters out of which one is mandatory and other two are
optional.
• $input_array (mandatory): Refers to the array that we want to operate on.
• **Output:**
• Array
• (
• [fruit1] => apple
• [fruit2] => banana
• [fruit3] => cherry
• )
• `
• array_unique()
• Removes duplicate values from an array.
• array_unique(array $array, int $sort_flags = SORT_STRING): array`
• <?php
• $arrayWithDuplicates = array('apple', 'banana', 'cherry', 'apple', 'banana');
•
• $uniqueArray = array_unique($arrayWithDuplicates);
•
• print_r($uniqueArray);
• ?>
• Array
• (
• [0] => apple
• [1] => banana
• [2] => cherry
• )
• array_count_values()
• Counts the occurrences of each unique value in an array.
• array_count_values(array $array): array`
• <?php
• $arrayWithValues = array('apple', 'banana', 'cherry', 'apple', 'banana');
•
• $valueCounts = array_count_values($arrayWithValues);
•
• print_r($valueCounts);
• ?>
• Array
• (
• [apple] => 2
• [banana] => 2
• [cherry] => 1
• )
• array_merge()
• Merges two or more arrays into a new array.
• array_merge(array $array1, array $array2, ...): array
• <?php
• $array1 = array('a', 'b');
• $array2 = array('c', 'd');
• $mergedArray = array_merge($array1, $array2);
• print_r($mergedArray);
• ?>
• Array
• (
• [0] => a
• [1] => b
• [2] => c
• [3] => d
• )
array_sum()
• These examples cover the basic usage of each function. You can adapt
them based on your specific use case and data.
array_search()
• Searches an array for a given value and returns the
corresponding key if successful.
• <?php
• $haystack = array('apple', 'banana', 'cherry');
•
• $position = array_search('banana', $haystack);
•
• echo "Position of 'banana': $position";
• ?>
• Position of 'banana': 1
array_reverse()
• Reverses the order of elements in an array.
• array_reverse(array $array, bool $preserve_keys = false): array`
• <?php
• $arrayToReverse = array('a', 'b', 'c');
•
• $reversedArray = array_reverse($arrayToReverse);
•
• print_r($reversedArray);
• ?>
• Array
• (
• [0] => c
• [1] => b
• [2] => a
• )
array_push()
• Pushes one or more elements onto the end of an array.
• array_push(array &$array, mixed $value1, mixed $value2, ...): int`
• <?php
• $stack = array("orange", "banana");
• $count = array_push($stack, "apple", "cherry");
• print_r($stack);
• echo "Number of elements after push: $count";
• ?>
• Array
• (
• [0] => orange
• [1] => banana
• [2] => apple
• [3] => cherry
• )
• Number of elements after push: 4
array_product()
• Calculates the product of array elements.
• array_product(array $array): number`
• <?php
• $numbers = array(2, 4, 6, 8);
• $product = array_product($numbers);
• echo "Product of array elements: $product";
• ?>
• Product of array elements: 384
array_pop()
• Removes and returns the last element of an array.
• array_pop(array &$array): mixed
• <?php
• $stack = array("orange", "banana", "apple");
• $lastElement = array_pop($stack);
• print_r($stack);
• echo "Popped element: $lastElement";
• ?>
• Array
• (
• [0] => orange
• [1] => banana
• )
• Popped element: apple