The Data Asylum

Programming, Databases and People

Differences Between PHP Arrays and Ruby Hashes

We've looked at the differences between Ruby and PHP arrays before. Now lets compare PHP arrays and Ruby hashes. They should be similar as all PHP arrays are implemented as hashes. There is however a crucial difference that can trip you up if you are switching from one language to another.

Referencing an index that hasn't been set is an error in PHP, but not in Ruby.

In PHP, retrieving a value for an index that you haven't used is a warning. Although warnings can be turned off it is best practice to develop with them turned on.

1
2
3
4
5
6
7
8
9
10
11
<?php

$a['key1'] = 'value1';
$a['key2'] = 'value2';

print $a['key5'];
/*
lang@virtualbox1:~/$ php hash.php
PHP Notice: Undefined index: key5 in /home/lang/hash.php on line 6
*/
?>

In Ruby you can set a default value for all keys that have not set a value. By default this value is nil.

1
2
3
4
5
6
7
8
9
10
a = Hash.new

a['key1'] = 'value1'
a['key2'] = 'value2'

puts a['key5']
=begin
lang@virtualbox1:~/$ ruby hash.rb
nil
=end

Ruby hashes are unordered (up to version 1.8). PHP arrays have an internal order seperate from their index.

When you loop through a PHP array, the values will be returned in the order they were added.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php

$a['key1'] = 'one';
$a['key0'] = 'zero';

foreach($a as $value) {
        print $value . "\n";
}
/*
lang@virtualbox1:~/$ php hash.php
one
zero
*/
?>

In Ruby 1.8 hashes are unordered, they could be retreived in any order that ruby decides is best. Ruby 1.9 changes this so that it works in the same way as the PHP example above.

1
2
3
4
5
6
7
8
9
10
11
12
13
a = Hash.new

a['key1'] = 'one'
a['key0'] = 'zero'

a.each_value do |value|
        puts value
end
=begin
lang@virtualbox1:~/$ ruby hash.rb
zero
one
=end

Is there anything that has been missed? Add a comment below.

Comments