15 1 0 4000 1 https://codeblock.co.za 300 true 0

array_map()

0 Comments

Programming Language

PHP [Versions: 4 >= 4.0.6, 5, 7, 8]

Syntax

Typical Usage

Applies a function to each element in an array.

Accepted Parameters

  • callback (function) (Nullable): The callable function that each element should run through. null can be passed as a value to the callback to perform a zip operation on multiple arrays. If only one array is provided, array_map() will return the input array.
  • $array (array) (Required): The array that should run through the callback function 
  • $arrays (array) (Optional): Additional arrays that should run through the callback function.

Return Value(s)

Returns an array containing the results of applying the callback function to the corresponding index of the arrays.

Notes

The returned array will preserve the keys of the array argument only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

Examples

Example 1

<?php
function plusOne($element) {
    return $element + 1;
}
$numbers = [1, 5, 6, 8];
$new_numbers = array_map('plus_one', $numbers);
print_r($new_numbers);

The above will add 1 to each element in the array and ouput:

Array (
   [0] => 2
   [1] => 6
   [2] => 7
   [3] => 9
)

Example 2: Validate Each Email Address in an Array

<?php
function validateEmails($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}
$emails = [
    'tony@stark.com', 'nick@shield.com',  'janedoeexample', 'johnsmith@example.com'
];
$validatedEmails = array_map('validateEmails', $emails);
print_r($validatedEmails);

The above will only return email addresses that pass validation otherwise an empty array element:

Array ( 
   [0] => tony@stark.com 
   [1] => nick@shield.com 
   [2] => 
   [3] => johnsmith@example.com 
)

Was This Helpful?

Previous Post
fgetcsv()
Next Post
implode()

0 Comments

Leave a Reply