0% found this document useful (0 votes)
4 views61 pages

PHP Array Basics and Functions Guide

Chapter 3 discusses arrays in PHP, detailing how to create indexed, associative, and multidimensional arrays. It covers various functions for manipulating arrays, including sorting, filtering, and modifying elements. Additionally, it provides examples for each type of array and function to illustrate their usage.

Uploaded by

vermanehu0101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views61 pages

PHP Array Basics and Functions Guide

Chapter 3 discusses arrays in PHP, detailing how to create indexed, associative, and multidimensional arrays. It covers various functions for manipulating arrays, including sorting, filtering, and modifying elements. Additionally, it provides examples for each type of array and function to illustrate their usage.

Uploaded by

vermanehu0101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Chapter 3.

Array
An array is a special variable, which can hold more
than one value at a time.
Create an Array in PHP
In PHP, the ar
ray() function is used to create an array:
array ();
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Associative arrays - Arrays with named keys

Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index
always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array
named $cars, assigns three elements to it, and
then prints a text containing the array values:
Example
<?php
$cars = array ("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1]
. " and " . $cars[2] . ".";
?>

Get The Length of an Array - The count() Function


The count() function is used to return the length
(the number of elements) of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
To loop through and print all the values of an
indexed array, you could use a forloop, like this:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


Associative arrays are arrays that use named keys
that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:
Example
<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>
"43");
echo "Peter is " . $age['Peter'] . " years
old.";
?>

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
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>
"43");

foreach($age as $x =>$y) {
echo "Key=" . $x . ", Value=" . $y;
echo "<br>";
}
?>

Multidimensional Arrays
The multidimensional array is an array in which
each element can also be an array and each
element in the sub-array can be an array or further
contain array within itself and so on.
<?php
// Define nested array
$contacts = array(
array(
"name" => "Peter Parker",
"email" => "peterparker@[Link]",
),
array(
"name" => "Clark Kent",
"email" => "clarkkent@[Link]",
),
array(
"name" => "Harry Potter",
"email" => "harrypotter@[Link]",
)
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>
PHP - Sort Functions For Arrays
The following are PHP array sort functions:
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending
order, according to the value
 ksort() - sort associative arrays in ascending
order, according to the key
 arsort() - sort associative arrays in
descending order, according to the value
 krsort() - sort associative arrays in
descending order, according to the key

Sort Array in Ascending Order - sort()


The following example sorts the elements of the
$cars array in ascending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>

The following example sorts the elements of the


$numbers array in ascending numerical order:
Example

<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>

Sort Array in Descending Order - rsort()


The following example sorts the elements of the
$cars array in descending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>

The following example sorts the elements of the


$numbers array in descending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>

Sort Array (Ascending Order), According to Value -


asort()
The following example sorts an associative array in
ascending order, according to the value:
Example
<?php
$age= array("Peter"=>"35", "Ben"=>"37", "Jo
e"=>"43");
asort($age);
?>

Sort Array (Ascending Order), According to Key -


ksort()
The following example sorts an associative array in
ascending order, according to the key:
Example
<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>
"43");
ksort($age);
?>

Sort Array (Descending Order), According to Value


- arsort()
The following example sorts an associative array in
descending order, according to the value:
Example
<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>
"43");
arsort($age);
?>

o/p:-Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

Sort Array (Descending Order), According to Key -


krsort()
The following example sorts an associative array in
descending order, according to the key:
Example
<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>
"43");
krsort($age);
?>
o/p:-Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37

1) PHP array_change_key_case() function


PHP array_change_key_case() function changes the
case of all key of an array.
Syntax
array array_change_key_case ( array $array [, int
$case = CASE_LOWER ] )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=
>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_U
PPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000
[RATAN] => 200000 )

2) PHP array_chunk() function


PHP array_chunk() function splits array into chunks.
By using array_chunk() method, you can divide
array into many parts.
Syntax
1. array array_chunk ( array $array , int $size [,
bool $preserve_keys = false ] )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=
>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] =>
250000 )
[1] => Array ( [0] => 200000 )
)

3) array_reverse() function
PHP array_reverse() function returns an array
containing elements in reversed order.
Syntax
1. array array_reverse ( array $array [, bool $pre
serve_keys = false ] )
Example
1. <?php
2. $season=array("summer","winter","spring","a
utumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer

4) array_search() function
PHP array_search() function searches the specified
value in an array. It returns key if search is
successful.
Syntax
1. mixed array_search ( mixed $needle , array $h
aystack [, bool $strict = false ] )
Example
1. <?php
2. $season=array("summer","winter","spring","a
utumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
2

5) array_intersect() function
PHP array_intersect() function returns the
intersection of two array. In other words, it returns
the matching elements of two array.
Syntax
1. array array_intersect ( array $array1 , array
$array2 [, array $... ] )
Example
1. <?php
2. $name1=array("sahil","john","vivek","smith");

3. $name2=array("umesh","sahil","kartik","smith
");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output: sahil
smith

6) array_combine()
array_combine () Creates an array by using one array for
keys and another for its values
Syntax:
array array_combine ( array $keys , array $v
alues )
Creates an array by using the values from the keys array
as keys and the values from thevalues array as the
corresponding values.

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>
The above example will output:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)

7) array_count_values
array_count_values () Counts all the values of an array
array array_count_values ( array $array )
array_count_values() returns an array using the values
of array as keys and their frequency in array as values.

<?php
$array = array(1, "hello", 1, "world", "hel
lo");
print_r(array_count_values($array));
?>

The above example will output:


Array
(
[1] => 2
[hello] => 2
[world] => 1
)

8) array_diff()
array_diff — Computes the difference of arrays
array array_diff ( array $array1 , array $ar
ray2 [, array $... ] )
Compares array1 against one or more other arrays and
returns the values in array1 that are not present in any of
the other arrays.
<?php
$array1 = array("a" => "green", "red", "blu
e", "red");
$array2 = array("b" => "green", "yellow", "
red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Multiple occurrences in $array1 are all treated the same


way. This will output :
Array
(
[1] => blue
)

9) array_filter()
array_filter — Filters elements of an array using a callback
function
Iterates over each value in the array passing them to
the callback function. If the callback function returns
true, the current value from array is returned into the
result array. Array keys are preserved.
Syntax:-
array array_filter ( array $array [, callab
le $callback [, int $flag = 0 ]] )
<?php
function odd($var)
{
// returns whether the input integer is
odd
return($var & 1);
}

function even($var)
{
// returns whether the input integer is
even
return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"


=>4,"e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";


print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

The above example will output:


Odd :
Array
(
[a] => 1
[c] => 3
[e] => 5
)
Even:
Array
(
[0] => 6
[2] => 8
[4] => 10
[6] => 12
)

10) array_unique()

This function removes duplicate values from


an array.

Syntax:-array_unique(input_array);

Example:

<?php

$states=array(“MH”,”JK”,”TN”,”JK”,”MH”);

print_r(array_unique($states));

?>
11)array_diff_assoc ()
array_diff_assoc — Computes the difference of arrays
with additional index check
array array_diff_assoc ( array $array1 , ar
ray $array2 [, array $... ] )
Compares array1 against array2 and returns the
difference. Unlike array_diff() the array keys are also used
in the comparison.
<?php
$array1 = array("a" => "green", "b" => "bro
wn", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "
red");
$result = array_diff_assoc($array1, $array2
);
print_r($result);
?>

The above example will output:


Array
(
[b] => brown
[c] => blue
[0] => red
)
11) array_sum()
array_sum — Calculate the sum of values in an array
syntax:-
number array_sum ( array $array )
ex:
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3


.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

The above example will output:


sum(a) = 20
sum(b) = 6.9
Adding and Removing Array Elements
1) array_push — Push one or more elements onto the end
of array
Syntax:-
int array_push ( array &$array [, mixed $..
. ] )
array_push() treats array as a stack, and pushes the
passed variables onto the end of array. The length
of array increases by the number of variables pushed.
Has the same effect as:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
2) array_pop() Pop the element off the end of array
Syntax:-
mixed array_pop ( array &$array )
array_pop() pops and returns the value of the last element
of array, shortening the array by one element.
<?php
$stack = array("orange", "banana", "apple",
"raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>
3) array_shift ()- Shift an element off the beginning of
array array_shift() shifts the first value of the array off
and returns it, shortening the array by one element and
moving everything down. All numerical array keys will be
modified to start counting from zero while literal keys won't
be touched.
Syntax:-
<?php
$stack = array("orange", "banana", "apple",
"raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

The above example will output:


Array
(
[0] => banana
[1] => apple
[2] => raspberry
)

4) array_unshift()
int array_unshift ( array &$array [, mixed
$... ] )
array_unshift() prepends passed elements to the front of
the array. All numerical array keys will be modified to
start counting from zero while literal keys won't be
changed.
<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry")
;
print_r($queue);
?>
Output:-
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
5. array_splice() Function
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.
Syntax
array_splice(array,start,length,array)

Parameter Description

array Required. Specifies an array

start Required. Numeric value. Specifies where the


function will start removing elements. 0 = the
first element. If this value is set to a negative
number, the function will start that far from the
last element. -2 means start at the second last
element of the array.
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.

array Optional. Specifies an array with the elements


that will be inserted to the original array. If it's
only one element, it can be a string, and does
not have to be an array.

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow
");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);

print_r($a1);
?>
Iterator functions in PHP
1) foreach()
The foreach construct provides an easy way to iterate over
arrays. foreach works only on arrays and objects, and will
issue an error when you try to use it on a variable with a
different data type or an uninitialized variable. There are
two syntaxes:
Syntax:-
foreach (array_expression as $value)
statement
foreach (array_expression as $key =>
$value)
statement
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with
the last element
?>
2) current ()— Return the current element in an array
Syntax:-
mixed current ( array $array )
Every array has an internal pointer to its "current" element,
which is initialized to the first element inserted into the
array.

3) end ():- Set the internal pointer of an array to its last


element
Syntax:-
mixed end ( array &$array )
end() advances array's internal pointer to the last
element, and returns its value.
4) next ()- Advance the internal pointer of an array
Syntax:-
mixed next ( array &$array )
next() behaves like current(), with one difference. It
advances the internal array pointer one place forward
before returning the element value. That means it returns
the next array value and advances the internal array
pointer by one.
5) prev() :— Rewind the internal array pointer
Syntax:-
mixed prev ( array &$array )
Rewind the internal array pointer.
prev() behaves just like next(), except it rewinds the
internal array pointer one place instead of advancing it.
<?php
$transport = array('foot', 'bike', 'car', '
plane');
$mode = current($transport); // $mode = 'fo
ot';
$mode = next($transport); // $mode = 'bi
ke';
$mode = current($transport); // $mode = 'bi
ke';
$mode = prev($transport); // $mode = 'fo
ot';
$mode = end($transport); // $mode = 'pl
ane';
$mode = current($transport); // $mode = 'pl
ane';
?>
6) reset () — Set the internal pointer of an array to its first
element
Syntax:-
mixed reset ( array &$array )
reset() rewinds array's internal pointer to the first element
and returns the value of the first array element.
<?php
$array = array('step one', 'step two', 'ste
p three', 'step four');
echo current($array) . "<br />\n"; // "step
one"
// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step
three"
// reset pointer, start again on step one
reset($array);
echo current($array) ."<br />\n"; // "step
one"

?>
Identifying Elements of an array
1.in_array() Function
The in_array() function searches an array for a specific value.
Note: If the search parameter is a string and the type parameter
is set to TRUE, the search is case-sensitive.
Syntax
in_array(search,array,type)

Parameter Description

search Required. Specifies the what to search for

array Required. Specifies the array to search

type Optional. If this parameter is set to TRUE, the


in_array() function searches for the search-string and
specific type in the array.

Example
Search for the value "Glenn" in an array and output some text:
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>

2. key() Function
The key() function returns the element key from the current
internal pointer position.
This function returns FALSE on error.
Syntax
key(array)
Example
Return the element key from the current internal pointer
position:

<?php
$people=array("Peter","Joe","Glenn","Cleveland");
echo "The key from the current position is: " . key($people);
?>
3. array_keys() Function
The array_keys() function returns an array containing the keys.
Syntax
array_keys(array,[value,strict])
Example
Return an array containing the keys:
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highl
ander");
print_r(array_keys($a));
?>

4.array_key_exists() Function
The array_key_exists() function checks an array for a specified
key, and returns true if the key exists and false if the key does
not exist.
Syntax
array_key_exists(key,array)
Example
Check if the key "Volvo" exists in an array:
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
[Link]()
This function does the same task as array_key_exist().but the
only difference is that the isset() does not return true for the keys
that correspond to NULL value,while array_key_exists() does.
Syntax :-
isset(array_name[key])
<?php
$states=array(“KN”=>”Karnataka”,”OR”=>”Orissa”);
var_dump(isset($states[“KN”]));
?>
[Link]()
To remove a key/value pair,call the unset() on array.
Syntax:
unset(array name[key]);
Example
<?php
$a=array(‘o’=>’one’,’t’=>’two’,’th’=>’three’);
unset($a[‘t’]);
print_r($a);
$v=array_values($a);//copy values from one array to another
//$v has values of $a with default numerical indexes
Print_r($v);?>

Determining Array size and Uniqueness


1)array_count_values
array_count_values — Counts all the values of an array
syntax:-
array_count_values ( array $array )
array_count_values() returns an array using the values
of array as keys and their frequency in array as values.
Examples
Example #1 array_count_values() example
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
2) count
count — Count all elements in an array, or something in an
object
syntax:
count ( mixed $array_)
Examples
Example #1 count() example
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
var_dump(count($b));
?>
The above example will output:
int(3)
int(3)

 Using Arrays
1) array_chunk()
array_chunk — Split an array into chunks
syntax:
array_chunk ( array $array , int $size )
Chunks an array into arrays with size elements. The last chunk
may contain less than size elements.
Examples
Example #1 array_chunk() example
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
?>

2) array_fill()
array_fill — Fill an array with values
syntax:
array_fill ( int $start_index , int $num , mixed $value ) : array
Fills an array with num entries of the value of
the value parameter, keys starting at the
start_index parameter.
examples
Example #1 array_fill() example
<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>
The above example will output:
Array
(
[5] => banana
[6] => banana
[7] => banana
[8] => banana
[9] => banana
[10] => banana
)

3) array_flip()
array_flip — Exchanges all keys with their associated values in
an array
syntax:
array_flip ( array $array ) : array
array_flip() returns an array in flip order, i.e. keys
from array become values and values from array become
keys.
Note that the values of array need to be valid keys, i.e. they
need to be either integer or string. A warning will be emitted if a
value has the wrong type, and the key/value pair in question will
not be included in the result.
Examples
Example #1 array_flip() example
<?php
$input = array("oranges", "apples", "pears");
$flipped = array_flip($input);

print_r($flipped);
?>
Output:
Array
(
[oranges] => 0
[apples] => 1
[pears] => 2
)

array_map()
array_map — Applies the callback to the elements of the given
arrays
syntax
array_map ( callable $callback , array $array1 [, array $... ] ) : ar
ray
array_map() returns an array containing the results of applying
the callback function to the corresponding index
of array1 (and ... if more arrays are provided) used as
arguments for the callback. The number of parameters that
the callback function accepts should match the number of
arrays passed to array_map().
Parameters
callback
Callback function to run for each element in each array.
array1
An array to run through the callback function.
Examples
Example #1 array_map() example

<?php
function cube($n)
{
return ($n * $n * $n);
}

$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);
?>
This makes $b have:
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
4) array_merge()
array_merge — Merge one or more arrays
Syntax:
array_merge ([ array $... ] ) : array
Merges the elements of one or more arrays together so that the
values of one are appended to the end of the previous one. It
returns the resulting array.
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one. If, however, the
arrays contain numeric keys, the later value will not overwrite
the original value, but will be appended.
Values in the input arrays with numeric keys will be renumbered
with incrementing keys starting from zero in the result array.
Examples
Example #1 array_merge() example
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapez
oid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
The above example will output:
Array
(
[color] =>green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] =>trapezoid)

Example #1 array_merge() example


<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapez
oid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
The above example will output:
Array
(
[color] =>green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] =>trapezoid

5) array_pad()
array_pad — Pad array to the specified length with a value
Syntax:-
array_pad ( array $array , int $size , mixed $value ) : array
array_pad() returns a copy of the array padded to size
specified by size with value value. If size is positive then
the array is padded on the right, if it's negative then on the left.
If the absolute value of size is less than or equal to the length
of the array then no padding takes place. It is possible to add
at most 1048576 elements at a time.
Parameters
array
Initial array of values to pad.
size
New size of the array.
value
Value to pad if array is less than size.
Return Values
Returns a copy of the array padded to size specified
by size with value value. If size is positive then the array
is padded on the right, if it's negative then on the left. If the
absolute value of size is less than or equal to the length of
the array then no padding takes place.
Examples
Example #1 array_pad() example
<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);


// result is array(12, 10, 9, 0, 0)
?>

6) array_replace()
array_replace — Replaces elements from passed arrays into the
first array
syntax:
array_replace ( array $array1 [, array $... ] ) : array
array_replace() replaces the values of array1 with values having
the same keys in each of the following arrays. If a key from the
first array exists in the second array, its value will be replaced
by the value from the second array. If the key exists in the
second array, and not the first, it will be created in the first array.
Parameters
array1
The array in which elements are replaced.
...
Arrays from which elements will be extracted. Values from
later arrays overwrite the previous values.
Examples

Example #1 array_replace() example


<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);


print_r($basket);
?>
The above example will output:

Array
(
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry
)

7) array_reverse()
array_reverse — Return an array with elements in reverse order
syntax:
array_reverse ( array $array [, bool $preserve_keys = FALSE ] )
: array
Takes an input array and returns a new array with the order of
the elements reversed.
Examples
Example #1 array_reverse() example
<?php
$input = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>
The above example will output:
Array
(
[0] =>php
[1] => 4
[2] => Array
(
[0] => green
[1] => red
)

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

[1] => 4
[2] =>php
)
Array
(
[2] => Array
(
[0] => green
[1] => red
)

[1] => 4
[0] =>php
)

8) array_slice()
array_slice — Extract a slice of the array
syntax
array_slice ( array $array , int $offset [, int $length = NULL [, b
ool$preserve_keys = FALSE ]] ) : array
array_slice() returns the sequence of elements from the
array array as specified by the offset
and length parameters.
Parameters
array
The input array.
offset
If offset is non-negative, the sequence will start at that
offset in the array.
If offset is negative, the sequence will start that far from
the end of the array.
Example #1 array_slice() examples
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"

// note the differences in the array keys


print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
The above example will output:
Array
(
[0] => c
[1] => d
)

array_walk() function
The array_walk() function runs each array element
in a user-defined function. The array's keys and
values are parameters in the function.
Syntax
array_walk (array, myfunction,
parameter...)

Parameter Description
array Required. Specifying an array

myfunction Required. The name of the user-


defined function

parameter,... Optional. Specifies a parameter to


the user-defined function. You can
assign one parameter to the
function, or as many as you like

Example 1
With a parameter:

<?php
function myfunction($value,$key,$p)
{
echo "$key $p $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue
");
array_walk($a,"myfunction","has the
value");
?>
Converting between arrays and variables
PHP compact() Function

The compact() function creates an array from


variables and their values.
Syntax
compact(var1, var2...)
parameter Values

Paramete Description
r

var1 Required. Can be a string with the


variable name, or an array of
variables

var2,... Optional. Can be a string with the


variable name, or an array of
variables. Multiple parameters are
allowed.
Example
Create an array from variables and their values:
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "41";

$result =
compact("firstname", "lastname", "age");
print_r($result);
?>
PHP extract() Function
Definition and Usage
The extract() function imports variables into the
local symbol table from an array.
This function uses array keys as variable names
and values as variable values. For each element it
will create a variable in the current symbol table.
This function returns the number of variables
extracted on success.

Syntax
extract(array, extract_rules, prefix)
Parameter Values

Parameter Description

array Required. Specifies the array to use

extract_rules Optional. The extract() function checks for


invalid variable names and collisions with
existing variable names. This parameter
specifies how invalid and colliding names
are treated.

Example
Assign the values "Cat", "Dog" and "Horse" to the
variables $a, $b and $c:
<?php
$a = "Original";
$my_array =
array("a" => "Cat","b" => "Dog", "c" => "Ho
rse");
extract($my_array);
echo"\$a = $a;\$b = $b;\$c = $c";
?>
PHP implode() Function
Definition and Usage
The implode() function returns a string from the
elements of an array.
Syntax
implode(separator,array)
Parameter Values

Paramete Description
r

separator Optional. Specifies what to put between the


array elements. Default is "" (an empty
string)

array Required. The array to join to a string

Example
Join array elements with a string:
<?php
$arr
= array('Hello','World!','Beautiful','Day!'
);
echo implode(" ",$arr);
?>

PHP explode() Function


Definition and Usage
The explode() function breaks a string into an
array.
Note: The "separator" parameter cannot be an
empty string.
Syntax
explode(separator,string,limit)
Parameter Values

Parameter Description

separator Required. Specifies where to break the string

string Required. The string to split


limit Optional. Specifies the number of array elements to
return.

Possible values:

 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()

 0 - Returns an array with one element


Example Break a string into an array:
<?php
$str = "Hello world. It's a beautiful
day.";
print_r (explode(" ",$str));
?>
Garbage Collection

PHP uses reference counting and copy on write to manage


memory. Copy-on-write ensures that memory isn’t wasted
when you copy values between variables and reference counting
ensure that the memory is return to the operating system when it
is no longer needed.
To implement memory management, symbol table is used.
When we copy the value from one variable to another, PHP
doesn't use additional memory, for copying of value. but it
updates the symbol table saying,” Both of these variable are
names for the same chunk of memory”.

Example: $col=array (“red”, 35,”blue”);


$copy=$col;
$col [1]=”yellow”;

Here we modify the copy for which PHP allocates memory. By


delaying the allocation and copying, PHP save time and memory
in a lot of situations. This is called ‘copy on write’.
Each value pointed to by a symbol table has a reference count, a
number that represents the number of ways there are to get to
that piece of memory after the initial assignment of the array to
$col and $col to $copy ,The array pointed to by the symbol
table entries for $col and $copy Has a reference count 2. in other
words, that memory can be reach two ways: through
$col or $copy .
When a variable goes out of scope the reference count of its
value is decreased by [Link] a variable is assigned a value in a
different area of memory, the reference count of the old value is
decreased by one.
When the reference count of a value reaches to 0, it’s
memory is freed. This is called as reference counting.
Isset() is used to check memory is allocated or not it give either
true or false result.

Unset() is used to free the memory of variable.

You might also like