Fitrar array PHP

Asked

Viewed 41 times

1

I have a PHP array, as illustrated below. I know I can filter them through (foreach, for example) and seeing if a value meets a certain criterion. But there is some simpler and faster way to make this filter?

<?php
$clientes = [
   ['id' => 1, 'nome' => 'Alefe', 'valor_autorizado' => 12159.99],
   ['id' => 2, 'nome' => 'Bete', 'valor_autorizado' => 35122.00],
   ['id' => 3, 'nome' => 'Guimel', 'valor_autorizado' => 86242.90]
   ['id' => 4, 'nome' => 'Dalete', 'valor_autorizado' => 2342.31]
];

For example, I want all customers with an authorized value greater than R $ 40.000,00.

1 answer

3


Yes. You can use the function array_filter. With this function you need to pass a array and a function of callback who will be responsible for returning true or false. In this function you can put your condition, for example:

<?php

$clientes = [
   ['id' => 1, 'nome' => 'Alefe', 'valor_autorizado' => 12159.99],
   ['id' => 2, 'nome' => 'Bete', 'valor_autorizado' => 35122.00],
   ['id' => 3, 'nome' => 'Guimel', 'valor_autorizado' => 86242.90],
   ['id' => 3, 'nome' => 'Juimel', 'valor_autorizado' => 86242.90],
   ['id' => 4, 'nome' => 'Dalete', 'valor_autorizado' => 2342.31]
];

/* Valor acima de 40.000 */
$clientes_filtrados = array_filter($clientes, function($arr) {
    return $arr["valor_autorizado"] >= 40000;
});

var_dump($clientes_filtrados);

/* Valor acima de 40.000 e que começa com a letra G */
$clientes_filtrados = array_filter($clientes, function($arr) {
    return $arr["valor_autorizado"] >= 40000 && preg_match("/^G/", $arr["nome"]);
});

var_dump($clientes_filtrados);

Demonstration in Ideone

  • Perfect, that’s just what I need! A question, I can apply more than one filter within the function?

  • 2

    Ahhh was faster :'( .... hehehe :D +1

  • @Andrey Yes. I edited my reply and added this option as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.