Ruby vs PHP Syntax Examples

I was mulling through some old code I had done on a drupal PHP based project a year ago and thought it might be interesting to show a few examples of syntax differences of basic PHP and Ruby one liners.

I only did around 15 of them but feel free to add your own in the comments if you have any that show off clear syntax differences between Ruby and PHP. You be the judge of course.

Examples of Ruby Syntax vs PHP

Ruby:

a = 1;b = 2;c = a + b;print c
#=> 3

PHP:

$a = 1;$b = 2; $c = $a + $b; print $c;
#=> 3

Ruby:

lang = Hash["Ruby" => "Because it's great", "PHP" => "It's terrible"]
 => {"Ruby"=>"Because it's great", "PHP"=>"It's terrible"}
lang["Ruby"]
=> "Because it's great"

PHP:

$cms = array("Drupal" => "Because it's great","Nuke" => "It's terrible"); echo $cms["Drupal"];
$cms = array("Drupal" => array("Because it's great","1","2"),"Nuke" => "It's terrible"); echo $cms["Drupal"][0];

Ruby:

count's from 0->100 by 5's
0.step(100,5) { |i| print i, " "}
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

PHP:

for ($i=0;$<=100;$i+=5); echo $i; done

Ruby:

takes a string of 5 numbers, puts it into an array. a[3] calls the 4th element and you get an output of 4 :)

a = "1 2 3 4 5".split.map { |s| s.to_i };a[3]
#=> 4

PHP:

Each string is an array of it's own ofcourse in php

$a = "1 2 3 4";list($b[],$b[],$b[],$b[]) = split(" ",$a); echo $b[3];

Ruby:

a = ('a'...'z');a.each { |char| print char + "\s" }
a b c d e f g h i j k l m n o p q r s t u v w x y => "a"..."z"

PHP:

for ($i=a;$<=z;$i+1); echo $i; done

Ruby:

3.5.round
#=>  4
3.4.round
#=> 3
a=["foo","bar"]; 4.times{print "#{a.reverse![0]}\s"}
=> bar foo bar foo

 

PHP:

$a=array('foo', 'bar'); while ($i++<4){ echo $a[0]; $a=array_reverse($a);}
$a=array('foo','bar');while($i++<4){echo"$a[0] ";$a=array_reverse($a);}