dukevin
dukevin

Reputation: 23178

Searching an array for an object's member variable

How would something like this be possible:

I have an object called Player:

class Player
{
  public $name;
  public $lvl;
}

and I have an array of these players in: $array.

For example $array[4]->name = 'Bob';

I want to search $array for a player named "Bob".

Without knowing the array key, how would I search $array for a Player named "Bob" so that it returns the key #? For example it should return 4.

Would array_search() work in this case? How would it be formatted?

Upvotes: 1

Views: 405

Answers (2)

Mike Purcell
Mike Purcell

Reputation: 19979

According to php docs, array_search would indeed work:

$players = array(
    'Mike',
    'Chris',
    'Steve',
    'Bob'
);

var_dump(array_search('Bob', $players)); // Outputs 3 (0-index array)

-- Edit --

Sorry, read post to quick, didn't see you had an array of objects, you could do something like:

$playersScalar = array(
    'Mike',
    'Chris',
    'Steve',
    'Bob'
);

class Player
{
  public $name;
  public $lvl;
}

foreach ($playersScalar as $playerScaler) {

    $playerObject = new Player;

    $playerObject->name = $playerScaler;

    $playerObjects[] = $playerObject;
}    

function getPlayerKey(array $players, $playerName)
{
    foreach ($players as $key => $player) {
        if ($player->name === $playerName) {
            return $key;
        }
    }
 }

var_dump(getPlayerKey($playerObjects, 'Steve'));    

Upvotes: 1

greut
greut

Reputation: 4363

Using array_filter will return you a new array with only the matching keys.

$playerName = 'bob';
$bobs = array_filter($players, function($player) use ($playerName) {
    return $player->name === $playerName;
});

Upvotes: 3

Related Questions