Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Array in PHP

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

Array in PHP

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

PHP ARRAY

Arrays in PHP is a type of data structure that allows us to store multiple


elements of similar data type under a single variable thereby saving us the
effort of creating a different variable for every data.
An array is created using an array() function in PHP.

ADVANTAGES OF USING 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.

There are basically three types of arrays in PHP:


 Indexed or Numeric Arrays: An array with a numeric index where values
are stored linearly.
 Associative Arrays: An array with a string index where instead of linear
storage, each value can be assigned a specific key.
 Multidimensional Arrays: An array which contains single or multiple
array within it and can be accessed via multiple indices.

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");
Example :-@indexed.php
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example :-@indexed.php

Traversing: We can traverse an indexed array using loops in PHP. We can loop
through the indexed array in two ways. First by using for loop and secondly by
using foreach
Example :-
<?php

// One way to create an indexed array


$name_one = array("rahul", "himanshi", "vanshika", "dheeraj", "dev");

echo "Accessing the 1st array elements directly:<br>";


echo $name_one[2], printf("\n");
echo $name_one[0], "\n";
echo $name_one[4], "\n";
echo "<br>--------------------------------------------------------------------
-----------<br>";

// Second way to create an indexed array


$name_two[0] = "abhi";
$name_two[1] = "pawan";
$name_two[2] = "princy";
$name_two[3] = "sujata";
$name_two[4] = "monika";

echo "Accessing the 2nd array elements directly:<br>";


echo $name_two[2], "<br>";
echo $name_two[0], "<br>";
echo $name_two[4], "<br>";

echo "<br>--------------------------------------------------------------------
-----------<br>";
// Indexed array with for loop
$arr=array("Abhishek","Himashi","Vanshika","Rahul");
for ($i=0; $i <count($arr) ; $i++) {
echo $arr[$i];
echo "<br>";
}
echo "<br>-------------------------------------------------------------------
------------<br>";
// Indexed array with foreach loop

$colors=['red','yellow','pink','purple'];

foreach($colors as $value){
echo $value . "<br>";
}

?>

PHP ASSOCIATVE 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.
There are two ways to define associative array:

1st way:

$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
We can traverse associative arrays in a similar way did in numeric arrays using
loops. We can loop through the associative array in two ways. First by using for
loop and secondly by using foreach.
Example :-
<?php

// Creating an Associative Array


$sal_one = [
"himanshi" => "100000 <br>",
"priyanka" => "5000.90 <br>",
"princi" => "failed <br>",
"rahul" => "error <br>",
"Raghav" => "456k <br>"
];

echo "<br> Looping using foreach: <br>";


foreach ($sal_one as $val => $value) {
echo "Salary of " . $val . " is " . $value . "\n";
}

echo "<br>Looping using for: <br>";


$keys = array_keys($sal_one);
$round = count($sal_one);

for ($i = 0; $i < $round; ++$i) {


echo $keys[$i] . " " . $sal_one[$keys[$i]] . "\n";
}
?>

MULTI DIMENSIONAL 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.
array (
array (elements...),
array (elements...),
...
)
<?php
// First way using for loop.
$emp = array
(
array(1,"Sonu",400000),
array(2,"Monu",500000),
array(3,"Ronak",300000)
);

for ($row = 0; $row < 3; $row++) {


for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br>";
}
echo "<br>-------------------------------------------------<br>";
// Second way using foreach loop.

$empl =[
[1,"Rohan","Manager",600000],
[2,"Mohan","Salesman",50000],
[3,"Sohan","Clerk",10000],
[4,"kamal","Driver",9000]

];
foreach($empl as $val)
{
foreach($val as $val1)
{
echo $val1." " ;
}
echo "<br>";
}

echo "<br>-------------------------------------------------<br>";
echo "<pre>";
print_r($empl);
echo "</pre>";
echo "<br>-------------------------------------------------<br>";
echo "<pre>";
var_dump($empl);
echo "</pre>";

?>

COMMON ARRAY FUNCTIONS


 array_change_key_case — Changes the case of all keys in an array
 array_chunk — Split an array into chunks
 array_column — Return the values from a single column in the input array
 array_combine — Creates an array by using one array for keys and another for its
values
 array_count_values — Counts the occurrences of each distinct value in an array
 array_diff_assoc — Computes the difference of arrays with additional index check
 array_diff_key — Computes the difference of arrays using keys for comparison
 array_diff_uassoc — Computes the difference of arrays with additional index check
which is performed by a user supplied callback function
 array_diff_ukey — Computes the difference of arrays using a callback function on the
keys for comparison
 array_diff — Computes the difference of arrays
 array_fill_keys — Fill an array with values, specifying keys
 array_fill — Fill an array with values
 array_filter — Filters elements of an array using a callback function
 array_flip — Exchanges all keys with their associated values in an array
 array_intersect_assoc — Computes the intersection of arrays with additional index
check
 array_intersect_key — Computes the intersection of arrays using keys for
comparison
 array_intersect_uassoc — Computes the intersection of arrays with additional index
check, compares indexes by a callback function
 array_intersect_ukey — Computes the intersection of arrays using a callback
function on the keys for comparison
 array_intersect — Computes the intersection of arrays
 array_is_list — Checks whether a given array is a list
 array_key_exists — Checks if the given key or index exists in the array
 array_key_first — Gets the first key of an array
 array_key_last — Gets the last key of an array
 array_keys — Return all the keys or a subset of the keys of an array
 array_map — Applies the callback to the elements of the given arrays
 array_merge_recursive — Merge one or more arrays recursively
 array_merge — Merge one or more arrays
 array_multisort — Sort multiple or multi-dimensional arrays
 array_pad — Pad array to the specified length with a value
 array_pop — Pop the element off the end of array
 array_product — Calculate the product of values in an array
 array_push — Push one or more elements onto the end of array
 array_rand — Pick one or more random keys out of an array
 array_reduce — Iteratively reduce the array to a single value using a callback
function
 array_replace_recursive — Replaces elements from passed arrays into the first array
recursively
 array_replace — Replaces elements from passed arrays into the first array
 array_reverse — Return an array with elements in reverse order
 array_search — Searches the array for a given value and returns the first
corresponding key if successful
 array_shift — Shift an element off the beginning of array
 array_slice — Extract a slice of the array
 array_splice — Remove a portion of the array and replace it with something else
 array_sum — Calculate the sum of values in an array
 array_udiff_assoc — Computes the difference of arrays with additional index check,
compares data by a callback function
 array_udiff_uassoc — Computes the difference of arrays with additional index check,
compares data and indexes by a callback function
 array_udiff — Computes the difference of arrays by using a callback function for data
comparison
 array_uintersect_assoc — Computes the intersection of arrays with additional index
check, compares data by a callback function
 array_uintersect_uassoc — Computes the intersection of arrays with additional index
check, compares data and indexes by separate callback functions
 array_uintersect — Computes the intersection of arrays, compares data by a callback
function
 array_unique — Removes duplicate values from an array
 array_unshift — Prepend one or more elements to the beginning of an array
 array_values — Return all the values of an array
 array_walk_recursive — Apply a user function recursively to every member of an
array
 array_walk — Apply a user supplied function to every member of an array
 array — Create an array
 arsort — Sort an array in descending order and maintain index association
 asort — Sort an array in ascending order and maintain index association
 compact — Create array containing variables and their values
 count — Counts all elements in an array or in a Countable object
 current — Return the current element in an array
 each — Return the current key and value pair from an array and advance the array
cursor
 end — Set the internal pointer of an array to its last element
 extract — Import variables into the current symbol table from an array
 in_array — Checks if a value exists in an array
 key_exists — Alias of array_key_exists
 key — Fetch a key from an array
 krsort — Sort an array by key in descending order
 ksort — Sort an array by key in ascending order
 list — Assign variables as if they were an array
 natcasesort — Sort an array using a case insensitive "natural order" algorithm
 natsort — Sort an array using a "natural order" algorithm
 next — Advance the internal pointer of an array
 pos — Alias of current
 prev — Rewind the internal array pointer
 range — Create an array containing a range of elements
 reset — Set the internal pointer of an array to its first element
 rsort — Sort an array in descending order
 shuffle — Shuffle an array
 sizeof — Alias of count
 sort — Sort an array in ascending order
 uasort — Sort an array with a user-defined comparison function and maintain index
association
 uksort — Sort an array by keys using a user-defined comparison function
 usort — Sort an array by values using a user-defined comparison function

---------------------------------------------------------------------------
STRING FUNCTIONS IN PHP
1) PHP strtolower() function
The strtolower() function returns string in lowercase letter.

2) PHP strtoupper() function


The strtoupper() function returns string in uppercase letter.

3) PHP ucfirst() function


The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.

4) PHP lcfirst() function


The lcfirst() function returns string converting first character into lowercase. It doesn't
change the case of other characters

5) PHP strlen() function


The strlen() function returns length of the string.

6) PHP strrev() function


The strrev() function returns reversed string.

7) PHP ucwords() function


The ucwords() function returns string converting first character of each word into
uppercase.

You might also like