filter array laravel code example

Example 1: php array filter syntax

$numbers = [2, 4, 6, 8, 10];

function MyFunction($number)
{
  return $number > 5;
}

$filteredArray = array_filter($numbers, "MyFunction");

/**
 * `$filteredArray` now contains: `[6, 8, 10]`
 * NB: Use this to remove what you don't want in the array
 * @see `array_map` when you want to alter/change elements
 * in the array.
 */

Example 2: filter laravel

public function index()
{
    $myStudents = [
        ['id'=>1, 'name'=>'Hardik', 'mark' => 80],
        ['id'=>2, 'name'=>'Paresh', 'mark' => 20],
        ['id'=>3, 'name'=>'Akash', 'mark' => 34],
        ['id'=>4, 'name'=>'Sagar', 'mark' => 45],
    ];
  
    $myStudents = collect($myStudents);
   
    $passedstudents = $myStudents->filter(function ($value, $key) {
        return data_get($value, 'mark') > 34;
    });
   
    $passedstudents = $passedstudents->all();
   
    dd($passedstudents);
}

Tags:

Php Example