Array Functions in PHP: PART 4

Introduction

In this article I describe the PHP array functions array_diff_ukey, array_fill and array_filter. To learn some other math functions, go to:

  1. Array Functions in PHP: PART 1
     
  2. Array Functions in PHP: PART 2
     
  3. Array Functions in PHP: PART 3

PHP array_diff_ukey  Function

The array_diff_ukey function compares the keys in two or more arrays, checking for differences, before comparing the keys in a user-defined function, then returns an array containing all the entries from array1 that are not present in any of the other arrays.

Syntax

array_diff_ukey(array1,array2,array3...........userDefined function)

Parameters in the array_diff_ukey Function

Parameter Description
array1 It specifies the array that is compared to the others.
array2 It specifies an array to compare against.
.................. It specifies more arrays to compare against.
userDefined function It specifies the name of the user-defined function.

Example of array_diff_ukey Function

<?php

functionmyfunction($array1,$array2)

{

if ($array1===$array2)

  {

  return 0;

  }

if ($array1>$array2)

  {

  return 1;

  }

else

  {

  return -1;

  }

}

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

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

echo "<pre>";

$result = array_diff_ukey($array1, $array2, "myfunction");

print_r($result);

?>
 

Output

array-diff-ukey-function-in-php.jpg 

PHP array_fill Function

The array_fill function is used to fill an array with values and returns the filled array.

Syntax

array_fill(start, number, array)

Parameter in array_fill Function

Parameter Description
start It specifies the starting index of the key.
number It specifies the number of elements to insert but must be greater than one.
array It specifies the value to be inserted.

Example of array_fill Function

<?php

echo "<pre>";

$a = array_fill(1, 2, 'banana');

print_r($a);

echo "<pre>";

$a = array_fill(1, 3, 'Apple');

print_r($a);

?>
 

Output

array-fill-function-in-php.jpg
 

PHP array_filter Function

The array_filter function is used to filter the elements of an array using a callback function and returns the filtered array.


Syntax
 

array_filter(array, function)

Parameter in array_filter Function

Parameter Description
start It specifies an array.
number It specifies the name of the user-defined function.

Example of array_filter Function

<?php

function myfunction($array1)

{

if ($array1==="Mango")

  {

  return true;

  }

else

  {

  return false;

  }

}

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

echo "<pre>";

$result = array_filter($array1,"myfunction");

print_r($result);

?>

Output

array-filter-function-in-php.jpg


Similar Articles