Filter elements of an array in php

0

my question is how to filter elements of an array, in this case I want the notes% co_from% to 6 to be filtered, my array is simple:

array:7 [▼
  0 => 1
  1 => 2
  2 => 4
  3 => 10
  4 => 7
  5 => 5
  6 => 10
]

Once filtered I would like to save them in a variable, I suppose that this doubt is super simple and basic. thank you very much.

    
asked by Freak24 12.12.2017 в 02:03
source

1 answer

2

Good morning,

I recommend you always look in the PHP documentation that is very complete and translated into Spanish.

In this case there is the function array_filter()

This can be passed up to three arguments

  • The array to filter
  • A callback (a function that will filter) optional
  • A flag (this is explained further in the documentation) optional

And it returns an array with the elements that passed the filter

For what you require, we would use array_filter() passing it the array and the callback in the following way:

$nuevoArray = array_filter( 
    [
      0 => 1,
      1 => 2,
      2 => 4,
      3 => 10,
      4 => 7,
      5 => 5,
      6 => 10,
    ], 
    function ($elemento) {
        return $elemento >= 6;
    }
);

Now $nuevoArray would have the elements that have a value >= to 6

I hope this helps you and that you have explained me well, anything you tell me that I try to explain better or if I did not answer the answer.

    
answered by 12.12.2017 / 02:22
source