Contents
What variables mean
php | perl | perlr | python
....
k = key
v = value
i = numeric iterator
b = boolean
s = string
n = number
a = array
rx = regular expressionBooleans
php
true, false
Evaluates to false: 0,'',null,false,array() (empty array)
Everything else evaluates to trueperl
0, '', undefined variables => all evaulate to false
1, everything else => all evaluate to truepython
True, False
Evaluates to false: False, None, '', 0, [], {}, ()
Everything else evaluates to trueruby
true,false - lowercase only
Evaluates to false: false, nil
Everything else evaluates to true, including 0, empty arrays and empty objectsNull + other
php
nullperl
nullpython
Noneruby
nilDivision
php
10/3 = 3.333python
10/3 # 3 - int/int is floored int
10/3.0 # 3.3333.. - int/float is standard float
10//3.0 # 3.0 int//float is floored floatruby
10/3 # 3 - int/int is floored int
10/3.0 # 3.3333.. - int/float is standard float
10/3.to_f # 3.3333..Numeric power
php
$n = pow(2,3);perl
$n = 2**3;python
n = 2**3python
n = pow(2,3)ruby
n = 2**3Mod
php
$n = 4%3; // 1
$n = 4.5%3; // 1
#res = $n == 1.5;python
n = 4.5%3ruby
n = 4.5%3For loop over an array
php
foreach($a as $v)php
foreach($a as $i => $v)php
for($i=0;$i<count($arr);$i++)perl
for $v (@array)perl
for ($i=0;$i<=$#a;$i++) {
  $v = $a[$i];
}python
for i in a:
  v = a[i]python
for v,i in zip(a,range(len(a))):ruby
a.each do |v|ruby
a.each_with_index do |v,i|ruby
a.each{|v| v }javascript
for (var i=0;i<a.length;i++) {
  var v = a[i];
}For loop over a hash
php
foreach ($arr as $k => $v) {}php
foreach ($arr as $v) {}php
array_walk($h,create_function('&$v,$k','
  $v += 1;
'));perl
for $k (keys %hash) {
  $v = $hash[$k];
}perl
for $s (%hash) {}python
for k in h:
  v = h[k]ruby
h.each do |k,v|javascript
for (var k in h) {
  var v = h[k];
}Statement modifiers slash tenary operators
php
$s = $b ? 'o' : 't';perl
print 'hello' if 1;python
s = 'o' if b else 't'ruby
print 'hello' if true
x = x + 1 while x < 100Scalar construction
php
$s = 'abc';perl
$s = 'abc';python
s = 'abc'ruby
s = 'abc'javascript
var s = 'abc';Scalar referencing
php
$s2 = &$s;perl
$s2 = \$s;Scalar cloning
php
$v2 = $v;perl
$v2 = $v;python
v2 = vruby
v2 = vTrim
python
s2 = s.strip()php
$s2 = trim($s);perl
sub trim { $_[0] =~ /^\s*?(.*?)\s*$/; return $1; }Upper case string
php
$s2 = strtoupper($s);python
s2 = s.upper()perl
$s2 = uc($s);Lower case strimg
php
$s2 = strtolower($s);python
s2 = s.lower()perl
$s2 = lc($s);Upper case first letter of a string
python
s2 = s.capitalize()perl
$s2 = ucfirst($s);perl
$s2 = ucfirst($s);Upper case first letter of each word - i.e. like excel proper()
php
$s2 = ucwords($s);python
s2 = s.title()Array construction
php
$a = array(1,2,3);python
arr = [1,2,3]perl
@arr = (1,2,3);perlr
$arr_ref = [1,2,3];perl
@arr = qw(cat dog fish);ruby
a = [1,2,3]ruby
a = %w[cat dog fish]Array cloning
php
$a2 = $a;perl
@a2 = @a;python
a2 = a[:]python
import copy
a2 = copy.deepcopy(a)ruby
a2 = a.cloneArray referencing
php
$a2 = $a;python
a2 = aruby
a2 = aHash construction with values
php
$h = array('k'=>'v','k2'=>'v2');perl
%h = ('k','v','k2','v2');perlr
$h_ref = {k => 'v', k2 => 'v2'};python
h = {'k':'v','k2':'v2'}ruby
h = {'k'=>'v','k2'=>'v2'}Hash add key / value
php
$a[$k] = $v;perl
$hash{$k} = $v;perlr
$hash->{$key};python
h[k] = vruby
h[k] = vHash cloning
php
$h2 = $h;perl
%h2 = %h;python
h2 = h.copy()Hash referencing
php
$h2 = &$h;python
h2 = hCreate a range
php
$a = range(0,5);perl
@a = 1..5;ruby
r = 0..2 # 0,1,2
r = 0...2 # 0,1Array push
php
$a[] = $v;php
array_push($a,$v);perl
push $a, $v;python
arr.append(v)ruby
a.push vruby
a << vArray pop
php
$v = array_pop($arr);perl
$v = pop @a;python
v = a.pop()ruby
v = a.popArray access last value
php
$v = $a[count($a)-1];php
$v = end($a)perl
$v = $a[-1];python
v = a[-1]ruby
v = a[-1]Array access single value
php
$v = $a[1];perl
$v = $arr[5];perlr
$v = $arr->[5];python
v = a[1]ruby
v = a[1]Array access multiple values
perl
@a2 = @a[1,3];python
a2 = a[1::2]ruby
a2 = a[2..4]ruby
a2 = a[2...4]Array modify value
php
$arr[5] = 10;python
arr[5] = 10;perl /* using $arr[5] because $v is a scaler, you don't use @arr[5] as you'd expect
$arr[5] = 10;perlr
$arr->[5] = 10;Value exists in array
php
$b = in_array($v,$a);perl
$v = grep $_ eq $v, @arrperl
$v = grep $v, @a;python
b = v in aruby
b = a.include? vArray comparison
ruby
b = a == a2Array length
php
n = count(a);perl
$n = scalar @a;ruby
n = a.lengthruby
n = a.nitemsArray sort
php
function _sort($a,$b) { return strcasecmp($a,$b); }
usort($a,'_sort');php
usort($a, create_function('$a,$b','return strcasecmp($a,$b);'));python
a.sort()ruby
a2 = a.sortruby
a.sort!ruby
a2 = a.sort {|x,y| a <=> b}Hash sort
php
ksort
uksortpython
a = h.keys()
a.sort()
for k in a:
  v = h[k]Key exists in hash
php
$b = isset($h[$k]);perl
$b = defined $arr[$k];python
b = a.has_key(k)ruby
b = h.include? kHash keys
php
$a = array_keys($h);perl
@a = keys %h;python
a = h.keys()Hash values
php
$a = array_values($h);perl
$a = values %h;String concatination
php
$s = 'a' . 'b';perl
$s = 'a' . 'b';python
s = 'a' + 'b'ruby
s = 'a' + 'b'Charcode
php
$s = chr($n);perl
$s = chr($n);ruby
dunno :-)String replace
php
$s = str_replace(match, replacement, $s);python
s2 = s.replace(match, replacement)Utf print
python
import codecs
sys.stdout = codecs.getwriter('utf')(sys.stdout) # sometimes you'll need thisSprintf
php
$s = sprintf('The %s brown %s','quick','fox');perl
$s = sprintf('The %s brown %s','quick','fox');python /* can use a scaler instead of an tuple if only a single value */
s = 'The %s brown %s' % ('quick','fox')String to array - split
php
$arr = preg_split("/$rx_delimeter/",$s);php
$arr = split($delimeter,$s);php
$arr = explode($delimeter,$s);perl
@a = split /$rx/, $s;Array to string - join
php
$s = implode($glue, $a);python
s = ''.join(a)Regular expression match
php
$b = preg_match("/$rx/",$s);php
preg_match_all("/$rx/",$s,$matches);perl
$b = $s =~ /$rx/;perl
$b = $s =~ m{$rx}; # or () <> || ## etc
$s = 'abc';
$rx = 'b';
$rx2 = 'd';
$res = $s =~ m{$rx} and not $s =~ m($rx2);ruby
n = s =~ /rx/ruby
n = s =~ /#{rx}/Regular expression replace
php
$s = preg_replace("/$rx/",$replacement,$s);perl
$s =~ s/$rx/$replacement/g;python
import re
$s = re.sub(rx,replacment,s)Array slice
php /* unknown */
$a = array_slice()perl
@a2 = @a[1..3];python
a2 = a[1:3]Array reverse
php
$a2 = array_reverse($a);perl
@a2 = reverse @a;python
a.reverse()Iterate line by line over a text file
php
$fh = fopen('data.txt');
while ($line = fgets($fh)) {
  $line = preg_replace('/[\r\n]/','',$line);
}
fclose($fh);php
$s = file_get_contents('data.txt');
$arr = preg_split('/\n/',$s);
foreach ($arr as $line) ...perl
open FH, 'data.txt';
for $line (<FH>) {
  chomp $line;
}
close FH;python
sys.stdout = codecs.getwriter('utf')(sys.stdout) # so that you can use the 'print' fn
import codecs
fh = codecs.open(filename,'r','latin-1')
for line in fh:python
fh = open(filename,'r')
for line in fh:Write to a file
php
$fh = fopen('out.txt','w');
fwrite($fh,$s);
fclose($fh);perl
open FH, '>out.txt';
print FH "Hello world\n";
close FH;python
f = open('out.txt', 'w')
f.write(s)
f.close()Read contents from an external website
php
$s = file_get_contents($url);python
import httplib
conn = httplib.HTTPConnection('www.somewhere.net.nz')
conn.request("GET", "/documents/index.html")
xhtml = conn.getresponse().read()Call a system command, get output
php
ob_start();
system($command);
$s = ob_get_clean();
print $s;Get arguments after calling from command line
php
$argv;perl
@ARGV;python
sys.argv;Cgi - get
php
$h = $_GET;Cgi - post
php
$h = $_POST;While loop
php /* don't think that it uses the word 'do' anywhere */
while ($b) {}perl
while ($b) {}Do loop
perl
do {} while ($b);Switch statement
php
switch ($var) {
  case 'one': // is in $var == 'one'
  default:
}Continue, break
php
foreach ($a as $v) {
  if ($b) continue;
  # do whatever
}perl
NAMED_LINE: for ($i=0;$i<scalar(@a); $i+=1) {
  next NAMED_LINE if ($i >= 5);
}python
for i in range(len(a)):
  if i >= 5: continueElse if
php
else if
elseifpython
elifperl
elsifDeleting varaiables
php
unset($var);python
del var;Print_r, var_dump
php
print_r($arr);
var_dump($var);perl
use Data::Dumper;
print Dumper \$var;perl
use Data::Dumper;
sub p { print $_[0].chr(10); }
sub d { print Dumper @_; }Mysql datetime to timestamp - 2008-10-14 12:00:04
php
$val = explode(" ",$datetime);
$date = explode("-",$val[0]);
$time = explode(":",$val[1]);
$timestamp = mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);Open a mysql database connection
php
$db = mysql_connect($host,$username,$password);
mysql_select_db($database);python
import MySQLdb, MySQLdb.cursors
db_connection = MySQLdb.connect(user=username, passwd=password, db=database , cursorclass=MySQLdb.cursors.DictCursor)
db = db_connection.cursor()Mysql query return assoc
php
$result = mysql_query($sql);
while ($row = mysql_assoc($result))python
db.execute(sql)
db.fetchall()python
db.execute(sql)
db.fetchone()Mysql insert
php
mysql_query($sql);python
db.execute(sql)
db_connection.commit()Die / exit
php
die($s);php /* i think */
exit($s);perl
die($s);perl
exit();python
import sys
sys.exit()Loop a filesystem directory
perl
sub loop_dir_recursive {
  my ($dir) = $_[0];
  for my $filepath(<$dir/*>) {
  $filename = $filepath;
  $filename =~ s|^.*/(.*)$|$1|g; # switch slash around for windows
  if (-d $filepath) {
  # is a directory
  loop_dir_recursive($filepath);
  } elsif (-f $filepath) {
  # is a file
  } else {
  # is something else ie symlink
  }
  }
}Recursively copy a directory with file filter
perl
use File::Copy 'cp';
use File::Path 'mkpath';
sub copy_files_recursive {
  my ($dir) = @_;
  for my $filepath (<$dir/*>) {
  if (-d $filepath) {
  next if ($filepath =~ m!(output|rips)!);
  copy_files_recursive($filepath);
  } elsif (-f $filepath) {
  if ($filepath =~ m!\.(png|gif|jpg)$!) {
  $target_filepath = 'output/test/' . $filepath;
  $target_path = $target_filepath;
  $target_path =~ s!/[^/]*?$!!g;
  if (not -e $target_path) {
  mkpath($target_path) or die ("$!");
  print "Creating $target_path".chr(10);
  }
  print "Copying $filepath -> $target_filepath".chr(10);
  cp $filepath, $target_filepath or die ("$!");;
  }
  } else {
  # is something else ie symlink
  }
  }
}Class
php
class MyClass extends MyParent {
  var $my_var = 15;
  function MyClass($arg) { // constructor - __construct for php5 ??
  $this->MyParent($arg); // super
  }
}python
class MyClass(MyParent):
  my_var = 15
  def __init__(self): # constructor
  self.my_other_var = 17ruby
class Child < Parent
  my_var :my_val
  attr_accessor :instance_var # writes getter + setter
  def initialize(v)
  @instance_var = v
  end
  def self.class_method
  end
  protected
  def pro
  end
  private
  def priv
  end
endConstruct object
php
$my_obj = new MyClass($arg);python
my_obj = MyClass(arg)Dynamic variable
php
${$var}Dynamic function
php
call_user_func($fn,$args);Import
php
require()
require_once()
include()
include_onceperl
use Data::Dumper;Define a constant
php
define('MY_CONST', 64);Escape html to display in a browser
php
$s = htmlentities($s);Escape string for database use
php /* i think */
$s = mysql_real_escape_string($s);Encode a string in windows-1251 (though is this ever actually used even if charset is specified in html?)
Encode a string in iso-8859-1 (latin-1)
Encode a string in utf