Chapter 2

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 66

Chapter 2

Arrays ,Functions and graphics


16 marks
Creating and Manipulating Array
• An array is a data structure that stores one or
more similar type of values in a single value.
• For example if you want to store 100 numbers
then instead of defining 100 variables its easy
to define an array of 100 length.
Types of array
• Numeric array
An array with a numeric index. Values are
stored and accessed in linear fashion
• Associative array
An array with strings as index. This stores
element values in association with key values
rather than in a strict linear index order.
• Multidimensional array
An array containing one or more arrays and
values are accessed using multiple indices
Numeric Array
These arrays can store numbers, strings and any
object but their index will be represented by
numbers. By default array index starts from zero.
<html>
<body>
Value is 1
<?php
Value is 2
/* First method to create array. */ Value is 3
$numbers = array( 1, 2, 3, 4, 5); Value is 4
foreach( $numbers as $value ) { Value is 5
Value is one
echo "Value is $value <br />"; Value is two
} Value is three
/* Second method to create array. */ Value is four
Value is five
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
</body></html>
<html>
<body>
<?php
$numbers=array(0=> "one“,1= "two“,2=> "three“
3=>"four“);
echo "Value is $numbers[1] <br />";
?>
</body></html>
2.Associative Arrays
• The associative arrays are very similar to
numeric arrays in term of functionality but
they are different in terms of their index.
Associative array will have their index as string
so that you can establish a strong association
between key and values.
<html>
<body>
<pre> array(3)
{ ["brand"]=>
<?php
string(4) "Ford"
$car = array("brand"=>"Ford",
"model"=>"Mustang", "year"=>1964);
["model"]=>
var_dump($car); string(7)
?> "Mustang"
["year"]=>
</pre> int(1964) }
</body>
</html>
Access Associative Arrays
• To access an array item you can refer to the key
name.
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
echo $car["model"];
?>
Change Value
• To change the value of an array item, use the key
name:
• <?php
• $car = array("brand"=>"Ford",
"model"=>"Mustang", "year"=>1964);
• $car["year"] = 2024;
• var_dump($car);
• ?>
Loop Through an Associative Array
• To loop through and print all the values of an associative
array, you could use a foreach loop, like this:
• Example
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}?>

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 $ mobile[0][0].": In stock: ".$ mobile[0][1].", sold: ".$ mobile[0][2].".<br>";


echo $ mobile[1][0].": In stock: ".$ mobile[1][1].", sold: ".$ mobile[1][2].".<br>";
echo $ mobile[2][0].": In stock: ".$ mobile[2][1].", sold: ".$ mobile[2][2].".<br>";
echo $ mobile[3][0].": In stock: ".$ mobile[3][1].", sold: ".$ mobile[3][2].".<br>";
?>
<?php
$mobile = array (
array(“samsung",22,18),
array(“Redmi",15,13),
array(“apple",5,2),
array(“oppo",17,15)
);
for($i=0;$i<4;$i++)
{echo “<ul>”
;
for($j=0;$j<4;$j++)
{
echo “<li>”.$mobile[$i][$j].”</li>”;

}
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: $AS is ASSAM $KR is KERELA $OR is ORRISA


list() function
• $array = array(1, 2, 3, 4);

• // Assign array values to variables
• list($a, $b, $c) = $array;

• // print all assigned values
• echo "a =", ($a), "\n";
• echo " b =", ($b), "\n";
• echo " c =", ($c), "\n";

• // Perform multiplication of
• // those assigned numbers
• echo "a*b*c =", ($a*$b*$c);
• ?>
Compact() function
• It is opposite to extract function.
• It returns array with all variables added to it.
• Each parameter can be either a string containing
name of variable or an array of variable names.
• Compact function created associative array
whose key value are the ariable name and
values are variable values.
• <?php
• $studname = “abc";
• $mobile = “986325687";
• $age = "41";
• $result = compact(“studname", “mobile", "age");
• print_r($result);
• ?>

Output
Array ( [studname] =>abc [mobile] => 986325687[age] => 41 )
Understanding implode() and explode() in PHP

• What are implode() and explode()?


• implode()
– Converts an array into a string
– Joins array elements with a string
• explode()
– Breaks a string into an array
– Splits a string based on a specified delimiter
implode() Function
• Syntax:
• string implode ( string $seperator , array $pieces )

• $separator : The string to be used between the


array elements.It is optional attribute.By default it
is an empty string.
• $pieces: The input array to be joined into a string.
• Example:
• $array = array('lastname', 'email', 'phone');
$comma_separated = implode(", ", $array);
• // Result: "lastname, email, phone"
explode() Function

• Syntax:
• array explode ( string $delimiter , string $string [, int
$limit = PHP_INT_MAX ] )

• $delimiter: The boundary string.


• $string: The input string to be split into array.
• $limit (optional): Maximum number of elements to
return.(positive,negative,zero)
• Greater than 0 - Returns an array with a maximum
of limit element(s)
• Less than 0 - Returns an array except for the last -
limit elements()
• Example:
• $string = "Hello, World, PHP";
• array = explode(", ", $string);
• // Result: ['Hello', 'World', 'PHP']

• 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);

• The keys become values, and values become keys.


• If duplicate values exist, only the last key will be kept in
the flipped array.

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

• Using unset() Function


– Removes a specified variable.
– Used to delete array elements.
• Example:
• $fruits = ["apple", "orange", "banana"];
• unset($fruits[1]);
• // Removes "orange"
Removing by Value
• array_search() and unset()
• array_search():
– Finds the key of a value in an array.
• Combining with unset():
– Delete an element by its value.
• Example:
• $colors = ["red", "green", "blue"];
• $key = array_search("green", $colors);
unset($colors[$key]); // Removes "green"
Removing Multiple Elements
• Using array_splice()
• array_splice():
– Removes a portion of the array and returns it.
– Can delete multiple elements.
• Example:
• $numbers = [1, 2, 3, 4, 5];
array_splice($numbers, 1, 2);
• // Removes elements at index 1 and 2
Filtering Elements
• array_filter() Function
• array_filter():
– Filters elements of an array using a callback function.
– Can be used to exclude specific elements.
• Example:
• $grades = ["A", "B", "C", "D", "F"];
• $grades = array_filter($grades, function ($grade)
{ return $grade != "D"; });
Conditional Deletion
• Removing Elements Based on Condition
• Using foreach Loop:
– Iterate through the array and remove elements
based on a condition.
• Example:
• $numbers = [10, 20, 30, 40, 50];
• foreach ($numbers as $key => $value)
• { if ($value > 30)
• { unset($numbers[$key]);
• }}
array_values()

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

Array ( [0] => green [1] => blue )


• <?php
• $cric=array("sachin","sehwag","rahul","ganguly","yuvraj");
• print_r(array_slice($cric,1,2));
• ?>
• Output:
• Array ( [0] =>sehwag [1] =>rahul )

• 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))

• $input_array = array('a', 'b', 'c', 'd', 'e');


array_chunk($input_array, 2, true)
• Output : Array ( [0] => Array ( [0] => a [1] => b ) [1]
=> Array ( [2] => c [3] => d ) [2] => Array ( [4] =>
e))
array_keys()
• The is a built-in function in PHP and is used to return either all the keys of and
array or the subset of the keys.

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

• $search_value (optional): Refers to the value of the array by which we want to


search the array for the key elements. If this parameter is passed then the
function will return keys corresponding to this element only otherwise it will
return all keys of the array.

• $strict (optional): Determines if strict comparison (===) should be used during


the search. false is the default value.
• Return Value: The function returns an array containing either all of the keys or
$input_array = ("one", "two", "three", "one", "four",
"three", "one", "one")
$search_value = "one"
• Output : Array ( [0] => 0 [1] => 3 [2] => 6 [3] => 7 )
array_keys()
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.
• $search_value (optional): Refers to the value of the array
by which we want to search the array for the key
elements. If this parameter is passed then the function
will return keys corresponding to this element only
otherwise it will return all keys of the array.
• $strict (optional): Determines if strict comparison (===)
should be used during the search. false is the default
value.
• <html>
• <body>
• <?php
• $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highland
er");
• print_r(array_keys($a,"Highlander"));
• ?>
• </body>
• </html>

Array ( [0] => Toyota )


array_key_exists()
• It is used to check whether a specific key or
index is present inside an array or not.
• The function returns true if the specified key is
found in the array otherwise returns false.
• The required key while specifying the array, is
skipped then it will generate the integer value for
the key, starting from 0 that will be incremented
by 1 for each value.
• boolean array_key_exists($index, $array)

• $index: This parameter is mandatory and refers


to the key that is needed to be searched for in
an input array.
• $array: This parameter is mandatory and refers
to the original array in which we want to search
the given key $index.
• <?php
• // Sample array
• $sampleArray = array(
• 'key1' => 'value1',
• 'key2' => 'value2',
• 'key3' => 'value3'
• );

• // Check if keys exist


• $keysToCheck = array('key1', 'key3', 'nonexistent_key');

• foreach ($keysToCheck as $key) {


• if (array_key_exists($key, $sampleArray)) {
• echo "Key '$key' exists in the array.<br>";
• } else {
• echo "Key '$key' does not exist in the array.<br>";
• }
• }
• ?>
array_splice()
• The array_splice() function removes selected elements from
an array and replaces it with new elements. The function also
returns an array with the removed elements.
• array_splice(array, start, length)
• arrayRequired. Specifies an array
• start Required. Numeric value. Specifies where the function
will start removing elements. If this value is set to a negative
number, the function will start that far from the last element.
• length Optional. Numeric value. Specifies how many
elements will be removed, and also length of the returned
array. If this value is set to a negative number, the function
will stop that far from the last element. If this value is not set,
the function will remove all elements, starting from the
position set by the start-parameter.
• <?php // Sample array
• $originalArray = array('apple', 'banana', 'cherry', 'date',
'rasberry');
• $removedElements = array_splice($originalArray, 1, 2);
• echo "Modified Array: ";
• print_r($originalArray);
• echo "Removed Elements: ";
• print_r($removedElements); ?>
• Output:
• Modified Array: Array ( [0] => apple [1] => date [2] =>
rasberry )
• Removed Elements: Array ( [0] => banana [1] =>
• array_combine()
• Creates an array by using one array for keys and another for its values.

• array_combine(array $keys, array $values): array


• <?php
• $keys = array('fruit1', 'fruit2', 'fruit3');
• $values = array('apple', 'banana', 'cherry');
• $combinedArray = array_combine($keys, $values);
• print_r($combinedArray);
• ?>

• **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()

• Calculates the sum of array elements.


• array_sum(array $array): number`
• <?php
• $numbers = array(2, 4, 6, 8);

• $sum = array_sum($numbers);

• echo "Sum of array elements: $sum";
• ?>
• Sum of array elements: 20

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

• array_search(mixed $needle, array $haystack, bool $strict =


false): mixed`

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

You might also like