1

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?

2 Answers 2

3

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

If OP using PHP5.3 this is the way!
@Juicy For the unlucky, create_function() is always there.
1

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

1 Comment

It will not, since OP clearly stated that array is array of objects and not scalars...

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.