Moazzem Hossen
Moazzem Hossen

Reputation: 2516

PHP array_filter() on multidimentional array by condition

I've the below array of users:

$users = [
  [name => 'Alice', age => 22],
  [name => 'Bob', age => 23],
  [name => 'Charlie', age => 19]
];

I'd like to create an array of users that are at least 20 years old. I tried:

$allowed_users = array_filter($users, function($user) {
  return $user->age >= 20;
});
var_dump($allowed_users);

Which returns an empty array. I suppose I'm doing something wrong with the callback function.

Upvotes: 0

Views: 36

Answers (4)

Yves Kipondo
Yves Kipondo

Reputation: 5623

Firstly the key of each sub user array is not wrap in double quote or single quote

$users = [
   ['name' => 'Alice', 'age' => 22],
   ['name' => 'Bob', 'age' => 23],
   ['name' => 'Charlie', 'age' => 19]
];

and you must access each sub array key using the key in bracket $users[1]['name'] return the name of the first user which is in the first sub array

$allowed_users = array_filter($users, function($user) {
  return $user['age'] >= 20;
});

Upvotes: 1

Rob Ruchte
Rob Ruchte

Reputation: 3707

You need to access your array members in array syntax, you are using object syntax.

<?php
$users = [
    ['name' => 'Alice', 'age' => 22],
    ['name' => 'Bob', 'age' => 23],
    ['name' => 'Charlie', 'age' => 19]
];

$allowed_users = array_filter($users, function($user) {
    return ($user['age'] >= 20);
});

var_dump($allowed_users);

Upvotes: 1

msg
msg

Reputation: 8181

You are using object notation with an array. It's a simple fix:

$users = [
  ['name' => 'Alice', 'age' => 22],
  ['name' => 'Bob', 'age' => 23],
  ['name' => 'Charlie', 'age' => 19]
];

$allowed_users = array_filter($users, function($user) {
  return $user['age'] >= 20;
});
var_dump($allowed_users);

And although it's not an error in itself, use quotes in your keys, otherwise the interpreter will throw a notice.

Upvotes: 1

shakogele
shakogele

Reputation: 399

You can use following Code:

function onStart(){
    $users = [
      ['name' => 'Alice', 'age' => 22],
      ['name' => 'Bob', 'age' => 23],
      ['name' => 'Charlie', 'age' => 19]
    ];

    $allowed_users = array_filter($users, function($user) {
      return $user['age'] >= 20;
    });
    var_dump($allowed_users);

}

Upvotes: 0

Related Questions