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

BCA 4 45 PHP Programming

Php programming

Uploaded by

Aarush Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

BCA 4 45 PHP Programming

Php programming

Uploaded by

Aarush Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PHP PROGRAMMING

UNIT-V
Array: Anatomy of an Array ,Creating index based and Associative array ,Accessing array, Looping with Index
based array, with associative array using each() and foreach(), Some useful Library function.

Simple arrays
Arrays are a special type of variable that can contain many variables, and hold them in a list.
For example, let's say we want to create a list of all the odd numbers between 1 and 10. Once we create the list, we
can assign new variables that will refer to a variable in the array, using the index of the variable.
To use the first variable in the list (in this case the number 1), we will need to give the first index, which is 0, since
PHP uses zero based indices, like almost all programming languages today.

$odd_numbers = [1,3,5,7,9];
$first_odd_number = $odd_numbers[0];
$second_odd_number = $odd_numbers[1];

echo "The first odd number is $first_odd_number\n";


echo "The second odd number is $second_odd_number\n";
output-The first odd number is 1
The second odd number is 3
We can now add new variables using an index. To add an item to the end of the list, we can assign the array with
index 5 (the 6th variable):
$odd_numbers = [1,3,5,7,9];
$odd_numbers[5] = 11;
print_r($odd_numbers);
Execute CodeArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Arrays can contain different types of variables according to your needs, and can even contain other arrays or
objects as members.
To delete an item from an array, use the unset function on the member itself. For example:
$odd_numbers = [1,3,5,7,9];
unset($odd_numbers[2]); // will remove the 3rd item (5) from the list
print_r($odd_numbers);
Execute CodeArray
(
[0] => 1
[1] => 3
[3] => 7
[4] => 9
)

Useful functions
The count function returns the number of members an array has.
$odd_numbers = [1,3,5,7,9];
echo count($odd_numbers);
Execute Code5-
The reset function gets the first member of the array. (It also resets the internal iteration pointer).
$odd_numbers = [1,3,5,7,9];
$first_item = reset($odd_numbers);
echo $first_item;
use the index syntax to get the first member of the array, as follows:
$odd_numbers = [1,3,5,7,9];
$first_item = $odd_numbers[0];
echo $first_item;
Execute Code
The end function gets the last member of the array.
$odd_numbers = [1,3,5,7,9];
$last_item = end($odd_numbers);
echo $last_item;
Execute Code
We can also use the count function to get the number of elements in the list, and then use it to refer to the last
variable in the array. Note that we subtract one from the last index because indices are zero based in PHP, so we
need to fix the fact that we don't count variable number zero.
$odd_numbers = [1,3,5,7,9];
$last_index = count($odd_numbers) - 1;
$last_item = $odd_numbers[$last_index];
echo $last_item;
Execute Code

Stack and queue functions


Arrays can be used as stacks and queues as well.
To push a member to the end of an array, use the array_push function:
$numbers = [1,2,3];
array_push($numbers, 4); // now array is [1,2,3,4];

// print the new array


print_r($numbers);
Execute Code
To pop a member from the end of an array, use the array_pop function:
$numbers = [1,2,3,4];
array_pop($numbers); // now array is [1,2,3];

// print the new array


print_r($numbers);
Execute Code
To push a member to the beginning of an array, use the array_unshift function:
$numbers = [1,2,3];
array_unshift($numbers, 0); // now array is [0,1,2,3];

// print the new array


print_r($numbers);
Execute Code
To pop a member from the beginning of an array, use the array_shift function:
$numbers = [0,1,2,3];
array_shift($numbers); // now array is [1,2,3];

// print the new array


print_r($numbers);
Execute Code

Concatenating arrays
We can use the array_merge to concatenate between two arrays:
$odd_numbers = [1,3,5,7,9];
$even_numbers = [2,4,6,8,10];
$all_numbers = array_merge($odd_numbers, $even_numbers);
print_r($all_numbers);
Execute Code

Sorting arrays
We can use the sort function to sort arrays. The rsort function sorts arrays in reverse. Notice that sorting is done
on the input array and does not return a new array.
$numbers = [4,2,3,1,5];
sort($numbers);
print_r($numbers);
Execute Code

Advanced array functions


The array_slice function returns a new array that contains a certain part of a specific array from an offset. For
example, if we want to discard the first 3 elements of an array, we can do the following:
$numbers = [1,2,3,4,5,6];
print_r(array_slice($numbers, 3));
Execute Code
We can also decide to take a slice of a specific length. For example, if we want to take only two items, we can add
another argument to the function:
$numbers = [1,2,3,4,5,6];
print_r(array_slice($numbers, 3, 2));
Execute Code
The array_splice function does exactly the same, however it will also remove the slice returned from the original
array (in this case, the numbers variable).
$numbers = [1,2,3,4,5,6];
print_r(array_splice($numbers, 3, 2));
print_r($numbers);
Execute Code
Exercise
1. Create a new array which contains the even numbers 2,4,6,8 and 10. The name of the new array should
be $even_numbers .
2. Concatenate the male_names and female_names arrays to create the names array.
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type
in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array.
All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Season are: summer, winter, spring and autumn
File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>

Output:
Season are: summer, winter, spring and autumn

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
PHP Indexed Array
PHP indexed array is an array which is represented by an index number by default. All elements of array are
represented by an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.
Definition
There are two ways to define indexed array:
1st way:
1. $size=array("Big","Medium","Short");
2nd way:
1. $size[0]="Big";
2. $size[1]="Medium";
3. $size[2]="Short";
PHP Indexed Array Example
File: array1.php
1. <?php
2. $size=array("Big","Medium","Short");
3. echo "Size: $size[0], $size[1] and $size[2]";
4. ?>
Output:
Size: Big, Medium and Short
File: array2.php
1. <?php
2. $size[0]="Big";
3. $size[1]="Medium";
4. $size[2]="Short";
5. echo "Size: $size[0], $size[1] and $size[2]";
6. ?>
Output:
Size: Big, Medium and Short
Traversing PHP Indexed Array
We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all the elements of
PHP array.
File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>

Output:
Size is: Big
Size is: Medium
Size is: Short
Count Length of PHP Indexed Array
PHP provides count() function which returns length of an array.
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Output:
3
PHP Associative Array
PHP allows you to associate name/label with each array elements in PHP using => symbol. Such way, you can
easily remember the element because each element is represented by label than an incremented number.
Definition
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="550000";
3. $salary["Vimal"]="250000";
4. $salary["Ratan"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
7. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
8. ?>
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
Traversing PHP Associative Array
By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
Output:
Key: Sonoo Value: 550000
Key: Vimal Value: 250000
Key: Ratan Value: 200000
PHP Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP
multidimensional array can be represented in the form of matrix which is represented by row * column.
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following tabular data. In this example, we
are displaying 3 rows and 3 columns.
File: multiarray.php Id Name Salary
1. <?php
1 sonoo 400000
2. $emp = array
3. ( 2 john 500000
4. array(1,"sonoo",400000), 3 rahul 300000
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
PHP 5 Array Functions
Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "values" array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key
comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key
comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a callback function
array_flip() Flips/Exchanges all keys with their associated values in an array
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key
comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key
comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made function, which returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array recursively
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
array_replace() Replaces the values of the first array with the values from following arrays
array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key
comparison function)
array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function
to compare the keys and a user-defined function to compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined
key comparison functions)
array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key
comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to
compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key
comparison functions)
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of an array
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an array
array_walk_recursive() Applies a user function recursively to every member of an array
arsort() Sorts an associative array in descending order, according to the value
asort() Sorts an associative array in ascending order, according to the value
compact() Create array containing variables and their values
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Returns the current key and value pair from an array
end() Sets the internal pointer of an array to its last element
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an associative array in descending order, according to the key
ksort() Sorts an associative array in ascending order, according to the key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive "natural order" algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
uasort() Sorts an array by values using a user-defined comparison function
uksort() Sorts an array by keys using a user-defined comparison function
usort() Sorts an array using a user-defined comparison function

You might also like