Search code examples
phparraysarray-filter

PHP how to filter multidimentional array


I have a multidimentional array that i want to validate

$new = [];
$old = [
        [
        'name'=>'ben',
        'age'=>20,
        ],
        [
        'name'=>'ben',
        'age'=>20,
        ],
        [
        'name'=>'ben',
        'age'=>##,
        ],

]

i want to move any sub array that have a value equal to "##" from the $old array to the $new array, so the result will be like this:

$old = [
        [
        'name'=>'ben',
        'age'=>20,
        ],
        [
        'name'=>'ben',
        'age'=>20,
        ],

];
$new = [
            [
            'name'=>'ben',
            'age'=>##,
            ],

    ]

i tried filter_arry and in_array without success


Solution

  • Just use foreach loop.

    The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

    There are two syntaxes:

    • foreach (array_expression as $value)
    • foreach (array_expression as $key => $value)

    The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

    The second form will additionally assign the current element's key to the $key variable on each iteration.

    Example:

    <?php
    $new = [];
    foreach ($old as $k => $v) {
        if ($v['age'] == '##') {
            $new[] = $v;
            unset($old[$k]);
        }
    }