array_key_exists
-
This function’s solution uses a Ruby
Hashobject since Ruby arrays don’t use associative key/value pairs. See Array for more details.To check if a key exists in a Ruby hash, we can use
Hash#include?.PHP
$colors = array('orange' => 1, 'yellow' => 4); $result = array_key_exists('orange', $colors); var_export($result); // => true
Ruby
colors = {:orange => 1, :yellow => 4} p colors.include?(:orange) # => true
In PHP, we use
array_key_existsinstead ofissetwhen it is important to know if a key actually exists, and is not just null.Hash#include?works similarly and will returntruefor a key even if it has anilvalue.PHP
$colors = array('orange' => 1, 'red' => null); $result = isset($colors['red']); var_export($result); // => false $result = array_key_exists('red', $colors); var_export($result); // => true
Ruby
colors = {:orange => 1, :red => nil} p colors[:red] # => nil p colors.include?(:red) # => true
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.

