7

given the following array:

Array
(
    [0] => Array
        (
            [id_contract] => 1
            [contract_months] => 5
            [months_with_expenses] => 1
        )

    [1] => Array
        (
            [id_contract] => 2
            [contract_months] => 12
            [months_with_expenses] => 0
        )

    [2] => Array
        (
            [id_contract] => 3
            [contract_months] => 1
            [months_with_expenses] => 1
        )

)

How can I remove all elements from the array where the key "contract_months" doesn't match the key "month_with_expenses"?

I'm using PHP.

Vickel
  • 7,879
  • 6
  • 35
  • 56
Psyche
  • 8,513
  • 20
  • 70
  • 85
  • 1
    Just as you described. Loop through it, check if the criterion is met and `unset` if so. –  Jan 05 '13 at 11:33
  • 3
    http://php.net/array_filter – Gordon Jan 05 '13 at 11:38
  • 1
    Like Gordon said array_filter could be used for this. Here is an example: $words = array_filter($words, create_function('$value','return strlen($value) > 3;')); – Jorge Aug 21 '13 at 17:24

3 Answers3

8

Try this:

foreach ($array as $key => $element) {
    if (conditions) {
        unset($array[$key]);
    }
}
suresh gopal
  • 3,138
  • 6
  • 27
  • 58
  • 2
    Please note that this solution does not reindex the array keys. To do it, you can add `$array = array_values($array);` at the end of your code. See this post for further details on deleting array items: [https://stackoverflow.com/questions/369602/deleting-an-element-from-an-array-in-php](https://stackoverflow.com/questions/369602/). – Zoup Aug 13 '21 at 13:24
4

You can try this :

foreach($arr as $key=>$value) {
    if($value['contract_months'] != $value['months_with_expenses']) {
       unset($arr[$key]);
    }
}
Angel
  • 333
  • 1
  • 5
0

A simple loop with an if condition and unset would work

<?php
    for( i=0; i<count($arr); i++){
        if($arr[i]['contract_months'] != $arr[i]['months_with_expenses']) {
            unset($arr[i]);
        }
    }
Pankrates
  • 3,074
  • 1
  • 22
  • 28