Skip to content

Instantly share code, notes, and snippets.

@mrbobbybryant
Last active April 22, 2016 06:50
Show Gist options
  • Select an option

  • Save mrbobbybryant/ec734df62cb3b2b9c3bc to your computer and use it in GitHub Desktop.

Select an option

Save mrbobbybryant/ec734df62cb3b2b9c3bc to your computer and use it in GitHub Desktop.
array_map tutorial
<?php
/**
* Template Name: array_map()
*
* @package WordPress
* @subpackage Twenty_fifteen
*/
/**
*
* A very simple example of how array_map works
*
*/
$array_map = array( 10, 20, 30 );
function multiple_array_values($n) {
return $n * 2;
}
$new_array = array_map( 'multiple_array_values', $array_map );
var_dump($new_array);
/**
*
* Behind the scenes this is what array_map is doing.
* Looping through an array and executing some sort of function.
*/
function another_example($array_map) {
$foreach_example = array();
foreach( $array_map as $value ) {
$foreach_example[] = $value * 2;
}
return $foreach_example;
}
var_dump(another_example($array_map));
/**
*
* In WordPress post Meta is a great use-case for array_map.
* Here I simply show you what get_post_meta will normally return.
* As well as, how to access the values.
*
*/
//$post_meta = get_post_meta( get_the_ID() );
$post_meta = array(
'first_name' => array(
'Bobby'
),
'channel' => array(
'Develop with WP'
),
'num_vids' => array(
32
),
'num_views' => array(
9000
),
'num_likes' => array(
22
)
);
var_dump( $post_meta['first_name'][0] );
/**
*
* But by using array_map we can make using post meta cleaner, and easier to do.
*
*/
function clean_post_meta( $a ) {
return $a[0];
}
$cleaned_post_meta = array_map( 'clean_post_meta', $post_meta );
var_dump( $cleaned_post_meta );
var_dump( $cleaned_post_meta['first_name']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment