array_keys
-
This function’s solution uses a Ruby
Hashobject since Ruby arrays don’t use associative key/value pairs. See Array for more details.To get the keys of an associative hash in Ruby, we can use the
Hash#keysmethod.PHP
$person = array('name' => 'Walter', 'age' => 25); $result = array_keys($person); var_export($result); // => array(0 => 'name', 1 => 'age')
Ruby
person = {:name => "Walter", :age => 25} p person.keys # => [:age, :name]
We can specify a value to match when retrieving keys by adding a second argument to PHP’s
array_keysfunction. We can achieve a similar result in Ruby using a block.PHP
$fruit = array('apple', 'orange', 'grape', 'apple'); $result = array_keys($fruit, 'apple'); var_export($result); // => array(0 => 0, 1 => 3)
Ruby
fruit = ["apple", "orange", "grape", "apple"] result = [] fruit.each_with_index do |value, key| result.push(key) if value == "apple" end p result # => [0, 3]
see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

