Skip to content

array_get_last_match

Tonya Mork edited this page Mar 12, 2017 · 1 revision

The array_get_last_match() function returns the last element that passes the "truth test" within the given callback.

You pass a callback to this function. Within your callback, you will receive both the key and value for each element. Then you determine if the element matches your "truth test" criteria. Your callback returns true or false.

If true, then array_get_last_match() returns the last occurrence. If there are no matches, it returns the default value.

Syntax:

array array_get_last_match( 
     array $subjectArray, 
     callable $truthTestCallback,
     [ mixed $defaultValue = null ]
);

Example

Here is a basic example to demonstrate how this function works.

Here is an array of users as our example dataset.

$users = array(
	102 => array(
		'user_id'    => 102,
		'name'       => 'Sally',
		'email'      => 'sally@foo.com',
		'has_access' => false,
	),
	103 => array(
		'user_id'    => 103,
		'name'       => 'Rose',
		'has_access' => true,
	),
	101 => array(
		'user_id'    => 101,
		'name'       => 'Tonya',
		'email'      => 'tonya@foo.com',
		'has_access' => true,
	),

	601 => array(
		'user_id'    => 601,
		'name'       => 'Bob Jones',
		'has_access' => false,
	),
);

Next, you need a callback to test if the user has access:

function user_has_access( $user_id, $user ) {
	if ( ! isset( $value['has_access'] ) ) {
		return false;
	}
	
	return $value['has_access'];
}

Next, let's get the first user that has access:

$user = array_get_last_match( $users, 'user_has_access', false );
// Returns
/**
 * array(
 *      'user_id'    => 101,
 *      'name'       => 'Tonya',
 *      'email'      => 'tonya@foo.com',
 *      'has_access' => true,
 * )
 */

Another Way to Do It

Using the same dataset, you use a closure too:

$user = array_get_last_match( $users, function ( $user_id, $user ) {
	if ( ! isset( $value['has_access'] ) ) {
		return false;
	}

	return $value['has_access'];
}, false );

Practical Example

Let's say you are working with an array of terms and you need to grab the last one that has more than one post assigned to it.

You may have a callback like this function:

/**
 * Checks if the term has more than one assignment.
 *
 * @since 1.0.0
 *
 * @param string $key
 * @param WP_Term $term
 *
 * @return bool
 */
function term_has_multiple_assignments( $key, $term ) {
	return $term->count > 1;
}

Let's say you have four categories: PHP, jQuery, SQL, and WordPress (in that order). PHP has 2 posts, jQuery has 1 post, SQL has 4 posts, and WordPress has 4 posts.

$terms = get_terms(array(
	'taxonomy'   => 'category',
	'hide_empty' => true,
));
$term = array_get_last_match( $terms, 'term_has_multiple_assignments', false );
// Returns the WordPress term object

« Back to Array API

Clone this wiki locally