0

I have array in php :

Array
    (
        [id] => 1
        [comp_id] => 1
        [transaction_purpose] => 0
        [source_of_funds] => 1
        [beneficiary_relationship] => 0
        [cus_occupation] => 0
        [cus_id_image_2] => 0
        [cus_id_image_3] => 0
        [ben_id_type] => 0
        [ben_id_number] => 1
    )

I want to get only array key=>value pair if the valie is 1.

result array should be:

Array
    (
        [id] => 1
        [comp_id] => 1
        [source_of_funds] => 1
        [ben_id_number] => 1
    )

I tried with:

$returnArray = array();
    foreach($mainArray as $r){
        if($r>0){
            array_push($returnArray, $mainArray);
        }
    }

But, It's giving me 4 times main array. Is there any way to achieve this? Thanks..

RNK
  • 5,582
  • 11
  • 65
  • 133

3 Answers3

5

Just use array_filter():

$newarray = array_filter($array, function($var) { return ($var === 1); });

$newarray = array_filter($array);

Demo

$array = array(
    'id' => 1,
    'comp_id' => 1,
    'transaction_purpose' => 0,
    'source_of_funds' => 1,
    'beneficiary_relationship' => 0,
    'cus_occupation' => 0,
    'cus_id_image_2' => 0,
    'cus_id_image_3' => 0,
    'ben_id_type' => 0,
    'ben_id_number' => 1
);

$newarray = array_filter($array);

print_r($newarray);

Array
(
    [id] => 1
    [comp_id] => 1
    [source_of_funds] => 1
    [ben_id_number] => 1
)
John Conde
  • 217,595
  • 99
  • 455
  • 496
3

Try this:

$returnArray = array_filter($result);

You can see PHP's array_filter function for more info.

Max
  • 913
  • 1
  • 7
  • 18
0

Well, what else are you expecting to happen?

        array_push($returnArray, $mainArray);

If you find an element which has >0 value, you push the ENTIRE original array onto the new one, not just the key/value you just tested.

You probably want:

$newarr = array();
foreach($mainArray as $key => $value) {
   if ($value > 0) {
        $newarr[$key] = $value;
   }
}
Marc B
  • 356,200
  • 43
  • 426
  • 500