lleoun
lleoun

Reputation: 477

Getting a new array with just the elements that contain certain value

I’ve got the following array:

$myArray
: array = 
  0: array = 
    0: string = 2012
    1: string = 1
    2: string = JOHN
  1: array = 
    0: string = 2012
    1: string = 2
    2: string = JOHN
  2: array = 
    0: string = 2012
    1: string = 3
    2: string = MARK

I’ve also have the variable $name. Let’s say that this time $name equals JOHN

What do I have to do to have a new array with just the elements that contain JOHN like this:

$myArray
: array = 
  0: array = 
    0: string = 2012
    1: string = 1
    2: string = JOHN
  1: array = 
    0: string = 2012
    1: string = 2
    2: string = JOHN

Thanks a million!

Upvotes: 0

Views: 42

Answers (2)

RobMasters
RobMasters

Reputation: 4148

The simplest way would be to use array_filter with a custom callback; in this case using a closure:

// $name is the variable containing 'JOHN'
$array2 = array_filter($array1, function($val) use ($name) {
   return $val[2] === $name;
});

Upvotes: 2

ClemKeirua
ClemKeirua

Reputation: 504

function search ($arr, $name){
    $result = array();
    foreach ($arr as $v) {
        if ($v[2] == $name)
            $result[] = $v;
    }
    return $result;
}

This function returns an array containing only the values you want.

Upvotes: 1

Related Questions