Array Functions in PHP: PART 2

Introduction

In this article I describe the PHP array functions array_combine, array_count_values and array_diff. To learn about some other math functions, go to:

  1. Array Functions in PHP: PART 1

PHP array_combine Function

The array_combine() function creates an array with one array for keys and another for its values.

Syntax

array_combine (keys, values)

Parameter in array_combine function

It takes two parameters; they are:

Parameter Description
keys It specifies the keys.
values It specifies the values.

Example of array_combine function

<?php

echo"<pre>";

$Fname=array('Sharad', 'Pramod', 'Sam');

$Lname = array('Gupta', 'Dubey', 'Hobbs');

$Fullname = array_combine($Fname, $Lname);

print_r($Fullname);

?>

Output

array-combine-function-in-php.jpg

PHP array_count_values function

The array_count_values() function returns an array using the values of the input array as the keys of the new array and the values of the new array are the number of occurences of the input array's values.

Syntax

array_count_values (array)

Parameter in array_count_values function

It takes one parameter; it is:

Parameter Description
array It specifies an array.

Example of array_count_values function

<?php

$array=array("bye", "hello", 1, "world", "hello",1);

echo "<pre>";

print_r(array_count_values($array));

?>

Output

array-count-values-function-in-php.jpg

PHP array_diff function

The array_diff() function computes the difference of arrays and returns an array with the key and values from the first array, if a value is not present in any of the other arrays.

Syntax

array_diff (array1, array2, array3,...............)

Parameter in array_diff function

Parameter Description
array1 It specifies an array, that is compared with others.
array2 It specifies an array to compare against.
..................... It specifies more arrays to compare against.

Example of array_diff function

<?php

$array1=array("a" => "Apple", "Mango", "Banana", "Mango");

$array2 = array("b" => "Apple", "Raspberry", "Mango");

$result = array_diff($array1, $array2);

print_r($result);

?>

Output

array-diff-function-in-php.jpg


Similar Articles