Array Functions in PHP: PART 7

Introduction

In this article I describe the PHP array functions array_key_exists, array_keys and array_map. 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
     
  4. Array Functions in PHP: PART 4
     
  5. Array Functions in PHP: PART 5
     
  6. Array Functions in PHP: PART 6
     

PHP array_key_exists Function

The PHP array_key_exists function deterimes whether the specified key or index exists in the given array or not and returns true if it exists otherwise false.

Syntax

array_key_exists(key, array)

Parameters

The parameters of the array_key_exists function are:

Parameter Description
key It specifies key.
array It  specifies an array.

Example

An example of the array_key_exists function is:

<?php
echo
"<pre>";
$
val = array("a" => "Apple", "b" => "Mango", "c" => "Orange", "Banana");
if(array_key_exists("
a",$val))
{
echo "
Key exists!";
}
else
{
echo "
key does not exists!";
}

?>

Output

array-key-exists-function-in-php.jpg
PHP array_keys Function

The PHP array_keys function accepts an array and returns a new array that contains only its keys.

Syntax

array_keys(array,values)

Parameters

The parameters of the array_keys function are:

Parameter Description
array It specifies an array.
values It  specifies values, then only keys with this values are returned.

Example

An example of the array_keys function is:

<?
php
echo
"<pre>";
$
val = array("a" => "Apple", "b" => "Mango", "c" => "Orange", "Banana");
echo "
Without Value Parameter: ";
print_r(array_keys($val));
echo "<
pre>";
echo "With Value Parameter: ";
print_r (array_keys($val,"Mango"));

?>

Output

array-keys-function-in-php.jpg

PHP array_map function

The array_map function sends each value of an array to the user-defined function and returns an array containing all the elements of arr1 after applying the user-defined function to each one.

Syntax

array_map( userDefinedFunction, array1, array2,........................)

Parameters

The parameters of the array_map function are:

Parameter Description
userDefinedFunction It specifies name of user defined function.
array1 It specifies an array.
array2 It  specifies an array.

Example

An example of the array_map function is:

<?php
function
myfunction($array1)
{

if
($array1==="Mango")
{

return
"orange";
}

return
$array1;
}
$
array1 = array(1 => "Apple",  2=> "Mango", 3 => "Orange", "Banana");
echo "
<pre>";
$result = array_map("myfunction",$array1);
print_r($result);

?>

Output

array-map-function-in-php.jpg


Similar Articles