0

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.

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

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;
});

Comments

0

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);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.