skip to Main Content

I have a multidimensional array (This data may also contain very large data).

In this data, in a column (example age column) I want to get data in which the data in a column (for example the age column) is within a certain range.

Data;

Array(

  1 => array(
     "id" => 1,
     "name" => "John",
     "age" => 18
  ),
  2 => array(
     "id" => 1,
     "name" => "Mike",
     "age" => 19
  ),
  3 => Array (
     "id" => 1,
     "name" => "Weber",
     "age" => 25
  )
  ...
)

Imagine data going like this. How can I return the elements of this array with an age range of 18-20? Remember, there may be hundreds of thousands of data. I need to keep the performance as high as possibl
e.

2

Answers


  1. Pippo gave you right answer but not detailed let me help you out with it.

    Basically you need to create a function which will return true if current filter is matched, like this:

    $dataArray = [["id" => 1, "name" => "John", "age" => 18], ["id" => 5, "name" => "Alex", "age" => 12]];
    function ageFilter($age){
      // ranging 18-20
      return in_array($age['age'], [18,19,20]);
    }
    $filteredArray = array_filter($dataArray, "ageFilter");
    // print_r($filteredArray) will contain John's data only.
    

    Detailed explanation of functions:

    Login or Signup to reply.
  2. As mentioned in the comment the best solution should be to use array_filter()

    A current version of its use can be:

    $fullArray = [/* the values*/]
    $filterdArray = array_filter($fullArray, fn ($item) => $item['age'] > 20); 
    

    assuming that you want the values greater than 20.

    You can replace the filter condition according to your needs by varying the callable, eg:

    // ages between 20 and 50
    fn ($item) => $item['age'] >= 20  &&  $item['age'] <= 50
    
    // ages equals to 20 or 50
    fn ($item) => $item['age'] == 20  ||  $item['age'] == 50
    

    for multiple non-contiguous values the best solution is using array_filter() as suggested by nikk.aa:

    fn ($item) => in_array($item['age'], [/* desired values */])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search