Tag Archives: Array

array_splice

It removes a portion of the array and replace it with something else

Example

<?php
echo “<pre>”;
$array = array(0 => ‘PHP’, 1 => ‘ASP’, 2 => ‘JSP’, 3 => ‘JS’);
$array1=array_splice($array,3);
print_r($array1);
?>

Output

Array
(
[0] => JS
)

array_slice

It extracts a slice of the array

Example

<?php
echo “<pre>”;
$array = array(0 => ‘PHP’, 1 => ‘ASP’, 2 => ‘JSP’, 3 => ‘JS’);
$array1=array_slice($array,2);
print_r($array1);
?>

Output

Array
(
[0] => JSP
[1] => JS
)

array_shift

It shift an element off the beginning of array

Example

<?php
echo “<pre>”;
$array = array(0 => ‘PHP’, 1 => ‘ASP’, 2 => ‘JSP’, 3 => ‘JS’);
array_shift($array);
print_r($array);
?>

Output

Array
(
[0] => ASP
[1] => JSP
[2] => JS
)

array_search

It searches the array for a given value and returns the corresponding key if successful

Example

<?php
$array = array(0 => ‘PHP’, 1 => ‘ASP’, 2 => ‘JSP’, 3 => ‘JS’);
echo $key = array_search(‘PHP’, $array);
?>

Output

0

array_reverse

It returns an array with elements in reverse order

Example

<?php
echo “<pre>”;
$array1 = array(‘WEB’ => array( “PHP”) , ‘ASP’ => array(“JAVA”, “JSP”), );
$array2 = array_reverse($array1);
print_r($array2);
?>

Output

Array
(
[ASP] => Array
(
[0] => JAVA
[1] => JSP
)

[WEB] => Array
(
[0] => PHP
)

)

array_replace

It replaces elements from passed arrays into the first array

Example

<?php
echo “<pre>”;
$array1 = array(‘WEB’ => array( “PHP”) , ‘ASP’ => array(“JAVA”, “JSP”), );
$array2 = array(‘JScript’ => array(‘VB’), ‘JS’ => array(‘C’));

$array2 = array_replace($array1, $array2);
print_r($array2);
?>

Output

Array
(
[WEB] => Array
(
[0] => PHP
)

[ASP] => Array
(
[0] => JAVA
[1] => JSP
)

[JScript] => Array
(
[0] => VB
)

[JS] => Array
(
[0] => C
)

)

array_replace_recursive

It replaces elements from passed arrays into the first array recursively

Example

<?php
echo “<pre>”;
$array1 = array(‘WEB’ => array( “PHP”) , ‘ASP’ => array(“JAVA”, “JSP”), );
$array2 = array(‘JScript’ => array(‘VB’), ‘JS’ => array(‘C’));

$array2 = array_replace_recursive($array1, $array2);
print_r($array2);
?>

Output

Array
(
[WEB] => Array
(
[0] => PHP
)

[ASP] => Array
(
[0] => JAVA
[1] => JSP
)

[JScript] => Array
(
[0] => VB
)

[JS] => Array
(
[0] => C
)

)

array_reduce

It reduce the array to a single value using a callback function

Example

<?php
function reduce($arg1, $arg2){
$arg1 += $arg2;
return $arg1;
}

$array1 = array(1, 7, 8, 4, 5);
$array2 = array_reduce($array1, “reduce”);
print_r($array2);
?>

Output

25

array_push

It pushes one or more elements onto the end of array

Example

<?php
echo “<pre>”;
$array = array(“PHP”, “ASP”);
array_push($array, “JSP”, “VB”);
print_r($array);
?>

Output

Array
(
[0] => PHP
[1] => ASP
[2] => JSP
[3] => VB
)