php - find subarrays with given subarray index with array_filter

php
voted: 0
vote
php array array-filter find

Finding subarrays having given property value. Condition for filtering can be used like: and, or

<?php

//declaring employees array
$employees = array(
	'0' => array('id' => 1, 'name' => 'john'),
	'1' => array('id' => 2, 'name' => 'jill'),
	'3' => array('id' => 3, 'name' => 'jenny')	
);

//find subarray where name is john
$johnSubArray = array_filter($employees, function($ar) {
                                return ($ar['name'] == 'john');
                            });

//printing subarray where name is john (array key is preserved)                            
print_r($johnSubArray);

/* output:                            
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => john
        )

)
*/

//find subarrays where name  is john or where name is jill
$johnAndJillSubarrays = array_filter($employees, function($ar) {
                                return ($ar['name'] == 'john' || $ar['name'] == 'jill');
                            });
                            
//print subarrays where name is john or name is jill                            
print_r($johnAndJillSubarrays);

/* output
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => john
        )

    [1] => Array
        (
            [id] => 2
            [name] => jill
        )

)
*/
working url: not entered
version: not entered
Leave a Comment:
Characters left:
No comments yet.