PHP : Array Functions Tutorial – Part 3

This is continuation to Array Functions Tutorial.

Previous Articles can be read from here

PHP : Array Functions Tutorial – Part 2
PHP : Array Functions Tutorial – Part 1
What is an Array? Functions of Array- Array Tutorials

Function : Check if array index is set and whether it has a value.
Function: Get Random Element from Array

Array Function – Part 3


array_diff()

This function compares the arrays passed and return the difference in them.

Syntax:

array_diff($array1, $array2, .....)

Example:


<?php
$array1 = array("apple", "ball", "cat", "dog");
$array2 = array("ball", "cat", "dog");
$result = array_diff($array1, $array2);

print_r($result);
?>

Output:


Array

(

[0]=>apple

)

array_intersect()

This function returns all the elements of array1 that are present in all other arrays passed. This function preserves the keys of array.

Syntax:


array_intersect($array1, $array2,....);

Example:


<?php
$array1 = array("apple", "ball", "cat", "dog");
$array2 = array("ball", "cat", "dog");
$result = array_intersect($array1, $array2);

print_r($result);
?>

Output:


Array
(
[1]=>ball
[2]=>cat
[3]=>dog
)

array_search()

This function search for a value in the given array and returns the key if the value is found.

Syntax:


array_search($needle,$haystack);

Example:


<?php
$array = array("apple", "ball", "cat", "dog");
$key = array_search('ball', $array);
echo $key;
?>

Output:


1

array_reverse()

This function returns an array with the elements in reverse order.

Syntax:


array_reverse($array);

Example:


<?php
$array = array("apple", "ball", "cat", "dog");
$new_array = array_reverse($array);
print_r($new_array);
?>

Output:


Array
(
[0]=>dog
[1]=>cat
[2]=>ball
[3]=>apple
)

array_values()

This function returns all the values from the input array and indexes numerically the array.

Syntax:


array_values($array)

Example:


<?php
$array = array('a'=>"apple", 'b'=>"ball", 'c'=>"cat", 'd'=>"dog");
$new_array = array_values($array);
print_r($new_aray);
?>

Output:


Array
(
[0]=>apple
[1]=>ball
[2]=>cat
[3]=>dog
)

Suggestion, Comments, Improvements and Questions are always welcome.

Reference:

PHP : Array Functions Tutorial – Part 2
PHP : Array Functions Tutorial – Part 1
What is an Array? Functions of Array- Array Tutorials

Function : Check if array index is set and whether it has a value.
Function: Get Random Element from Array
PHP.net

Comments are closed.