Mythriel
Mythriel

Reputation: 1380

How to filter an array based on 2 values

I have an array containing multiple rowsets, including type, title and description....i need to filter the array and display only those rowsets based on type = "education" and type = "experience".

foreach () { if (type = 'experience') ..do something / else ... do something else} ?

Upvotes: 0

Views: 2928

Answers (2)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

Use array_filter

function myfilter($row){
    return ($row['type']=='experience'|| $row['type']=='education'); 
}
$result = array_filter($input_array, 'myfilter');

array_filter function preserves the keys of the original array. if you dont want this behavior use array_values

$result = array_values(array_filter($input_array, 'myfilter'));

Upvotes: 4

Poonam
Poonam

Reputation: 4631

$array = array(array('type'=>'experience','title'=>'xyz','des'=>'dfasdasdasdas'),
        array('type'=>'education','title'=>'xddfdfyz','des'=>'dfasdasdasdas'),
    array('type'=>'dsad','title'=>'afdf','des'=>'dfasdasdasdas'),
    array('type'=>'education','title'=>'gfdsfr','des'=>'dfasdasdasdas'));

foreach($array as $value){
    if($value['type'] == 'experience'){
        //do your stuff
    }else if ($value['type'] == 'education'){
        //do your stuff
    }else{
        //do your stuff
    }
}

assuming your array sructure as shown,You can change foreach loops if condition as

 if($value['type'] == 'experience' || $value['type'] == 'education'){
//do your stuff
}else{
//do your stuff
}

Upvotes: 0

Related Questions