The Data Asylum

Programming, Databases and People

Major Differences Between PHP and Ruby Arrays

PHP has a single array type, where as Ruby has Array and Hash, which covers the same functionality. In this article i'll go though the three major logical differences between PHPs array type and Rubys Array class. We compare PHP arrays and Ruby Hashes in separate post.

Firstly,

PHP arrays have an internal order separate from their index.

Lets look at a simple example. In php the order you insert values into an array determines the order that php will return them using foreach.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$a[1] = 'one';
$a[0] = 'zero';

foreach($a as $value) {
        print $value . "\n";
}

/*
lang@virtualbox1:~/arrays$ php array.php
one
zero
*/
>?

Ruby on the other hand uses the key or index of the array to determine the order, regardless of order in which the values are inserted.

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

a[1] = 'one'
a[0] = 'zero'

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

Secondly,

Ruby arrays always start at 0 and end at the highest index. PHP arrays only contain the keys that have been entered.

In the example below, PHP will output the two array values that are set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$a[2] = 'two';
$a[4] = 'four';

foreach($a as $value) {
        print $value . "\n";
}

/*
lang@virtualbox1:~/arrays$ php array.php
two
four
*/
?>

In the ruby example, not only are the two values output, but an attempt is made to get the value from every index between 0 and the highest index set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
a = Array.new

a[2] = 'two'
a[4] = 'four'

a.each do |value|
        puts value
end
=begin
lang@virtualbox1:~/arrays$ ruby array.rb
nil
nil
two
nil
four
=end

This leads to another difference…

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

The following code produces a PHP notice. Notices are a low severity error, and are usually turned off on production servers. However it is considered good practice to develop with notices turned on.

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

$a[2] = 'two';
$a[4] = 'four';

print $a[5];

/*
lang@virtualbox1:~/arrays$ php array.php
PHP Notice: Undefined offset: 5 in /home/lang/arrays/array.php on line 6
*/
?>

Ruby on the other hand does not consider this an error. It will return the nil value which is 'kind of' like PHPs null.

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

a[2] = 'two'
a[4] = 'four'

puts a[5]
=begin
lang@virtualbox1:~/arrays$ ruby array3.rb
nil
=end

So what are your experiences switching between PHP and Ruby. Let me know in the comments below.

Comments