Assignment

                
$a = 1;
$b = 'Hello';
$c = ['array','of','items']; // array
$d = ['key' => 'value']; // Uses arrays as dictionaries
$e = true; // 'True' also accepted
                
            
                
a = 1
b = 'Hello'
c = ['list','of','items'] # list
d = {'key': 'value'} # dict
e = True # 'true' is an error
                
            
                
let a = 1; // Or 'const a = 1;' to prevent re-assignment
let b = 'Hello'; // $b (etc) is allowed but uncommon
let c = ['array','of','items']; // array
let d = {key: 'value'}; // anonymous object
let e = true; // 'True' is an error
                
            
                
int a = 1; Integer aa = new Integer(2);
String b = "Hello";
String[] c = { "array", "of", "items" }; // array

boolean e = true; // 'True' is an error
                
            

Arithmetic

                
$a = 1;
$a++; // 2
$a+=2; // 4
$a--; // 3

$a = 4 / 2; // 2

$a = 3 % 3; // 1 (modulo)
$a = 3 ** 2; // 9 (power)
                
            
                
a = 1
a += 1 # 2 - no '++' operator
a += 2 # 4
a -= 1 # 3

a = 4 / 2 # 2.0
a = 5 // 2 # 2 (integer division)
a = 3 % 2 # 1 (modulo)
a = 3 ** 2 # 9 (power)
                
            
                
let a = 1;
a++; //2
a+=2; //4
a--; //3

a = 4 / 2 // 2.0

a = 3 % 2 // 1 (modulo)
a = 3 ** 2 // 9 (power)
                
            
                
int a = 1;
a++; //2
a+=2; //4
a--; //3

a = 5 / 2 // 2
double d = 5.0 / 2 // 2.5

a = 3 % 2 // 1 (modulo)
a = (int)Math.pow(3, 2) // 9 (power - no operator)
                
            

Strings

                
$a = 'Hello' . ' World';

$greeting = 'Hello';
$subject = 'World';
$message = "$greeting $subject"; // variants exist
$shout = strtoupper($message);
                
            
                
a = 'Hello' + ' World'

greeting = 'Hello'
subject = 'World'
message = f'{greeting} {subject}'
shout = message.upper()
                
            
                
let a = 'Hello' + ' World';

let greeting = 'Hello';
let subject = 'World';
let message = `${greeting} ${subject}`;
let shout = message.toUpperCase();
                
            
                
String a = "Hello" + " World";

String greeting = "Hello";
String subject = "World";
String message = String.format("%s %s", greeting, subject);
String shout = message.toUpperCase();
                
            

Functions

                
function increase($number, $by=1) {
  return $number + $by;
}

increase(7); // 8
increase(27, 15); // 42
                
            
                
def increase(number, by=1):
  return number + by


increase(7); # 8
increase(27, 15); # 42
                
            
                
function increase(number, by=1) {
  return number + by;
}

increase(7); // 8
increase(27, 15); // 42
                
            
                
// Functions outside of classes are not supported
                
            

Control Flow

                
if ($a === 42) {
  print('You have the answer');
} else if ($a > 42) {
  print('Too high!');
} else {
  print('Too low!');
}


switch($whichThing) {
  case 'thing1':
    handleThing1();
    break;

  case 'thing2':
    handleThing2();
    break;

  default:
    panic();
    break;
}
                
            
                
if a == 42:
  print('You have the answer');
elif a > 42:
  print('Too high!')
else:
  print('Too low!')



# Python has no switch/case construct, use if/elif…/else
                
            
                
if (a === 42) {
  console.log('You have the answer');
} else if (a > 42) {
  console.log('Too high!');
} else {
  console.log('Too low!');
}


switch(whichThing) {
    case 'thing1':
        handleThing1();
        break;

    case 'thing2':
        handleThing2();
        break;

    default:
        panic();
        break;
}
                
            
                int a;
if (a == 42) {
  System.out.println("You have the answer");
} else if (a > 42) {
  System.out.println("Too high!"); // block statement
} else
  System.out.println("Too low!"); // or single statement!


// switch non-null String, integer types, enums only
String whichThing="";
switch(whichThing) {
  case "thing1": {
    handler.handleThing1();
    break;
  }

  case "thing2": {
    handler.handleThing2();
    break;
  }

  default: {
    handler.panic();
    break;
  }
}
                
            

Loop in range

                
for ($i = 10; $i > 0; $i--) {
  print("$i green bottles, standing on a wall\n");
}
                
            
                
for i in range(10, 0, -1):
  print(f"{i} green bottles, standing on a wall")

                
            
                
for (i = 10; i > 0; i--) {
  console.log(i + " green bottles, standing on a wall");
}
                
            
                
for (int i = 10; i > 0; i--) {
  System.out.println(i + " green bottles, standing on a wall");
}
                
            

Loop array (natively)

                
$colors = ['red', 'green', 'blue'];
foreach ($colors as $color) {
  print("I see a $color bottle\n");
}
                
            
                
colors = ['red', 'green', 'blue']
for color in colors:
  print(f"I see a {color} bottle")

                
            
                
let colors = ['red', 'green', 'blue'];
for (const color of colors) { // 'var' or 'let' can be used here
  console.log(`I see a ${color} bottle`);
}
                
            
                
String[] colors = {"red", "green", "blue"};
for (String color: colors) {
  System.out.printf("I see a %s bottle\n", color);
}
                
            

Loop array (by index)

                
$colors = ['red', 'green', 'blue'];
for ($i=0; $i < count($colors); $i++) {
  print("I see a ${colors[$i]} bottle\n");
}
                
            
                
colors = ['red', 'green', 'blue']
for i in range(0, len(colors)):
  print(f"I see a {colors[i]} bottle")

                
            
                
let colors = ['red', 'green', 'blue'];
for (let i in colors) {
  console.log(`I see a ${colors[i]} bottle`);
}
                
            
                
String[] colors = {"red", "green", "blue"};
for (int i =0 ; i < colors.length; i++) {
  System.out.printf("I see a %s bottle\n", colors[i]);
}
                
            

Loop array (with index)

                
$colors = ['red', 'green', 'blue'];
for ($i=0; $i < count($colors); $i++) {
  print("$i) I see a ${colors[$i]} bottle\n");
}
                
            
                
colors = ['red', 'green', 'blue']
for (i, color) in enumerate(colors):
  print(f"{i}) I see a {color} bottle")

                
            
                
let colors = ['red', 'green', 'blue'];
for (let i=0; i < colors.length; i++) {
  console.log(`${i}) I see a ${colors[i]} bottle`);
}
                
            
                
String[] colors = {"red", "green", "blue"};
for (int i =0 ; i < colors.length; i++) {
  System.out.printf("%d) I see a %s bottle\n", i, colors[i]);
}
                
            

Loop map

                
// Mapping type is associative array
$things = ['apple' => 'red', 'tree' => 'green', 'bottle' => 'blue'];
foreach ($things as $thing => $color) {
  print("I see a $color $thing\n");
}
                
            
                
# Mapping type is dict
things = { 'apple': 'red', 'tree': 'green', 'bottle': 'blue'}
for (thing, color) in things.items():
  print(f"I see a {color} {thing}")

                
            
                
// Mapping type is anonymous object
const things = { apple: 'red', tree: 'green', bottle: 'blue'}
for (let thing in things) {
  if(things.hasOwnProperty(thing)) {
    console.log(`I see a ${things[thing]} ${thing}`);
  }
}
                
            
                
// No primitive mapping type
                
            

Split & join

                
$letters = ['a','b','c','d','e'];
$alpha = implode($letters); // 'abcde'
$csv = implode(',', $letters); // 'a,b,c,d,e'
$lettersAgain = explode( ',', $csv);
                
            
                
letters = ['a','b','c','d','e']
alpha = ''.join(letters)
csv = ','.join(letters)
letters_again = csv.split(',')
                
            
                
let letters = ['a','b','c','d','e'];
let alpha = letters.join('');
let csv = letters.join(',');
let lettersAgain = csv.split(',');
                
            
                
String[] letters = {"a", "b", "c", "d", "e"};
String alpha = String.join("", letters);
String csv = String.join(",", letters);
String[] lettersAgain = csv.split(",")
                
            

Arrays

                
$letters = ['a','b','c','d','e'];
$letters[] = 'f';
count($letters); // 6
in_array('b', $letters); // true
array_search('d', $letters); // 3
array_slice($letters, 2, 3); // ['c','d','e']
['a','b','c'] + ['d','e','f','g']; // ['a','b','c','g']
                
            
                
letters = ['a','b','c','d','e']
letters.append('f')
len(letters) # 6
'b' in letters # True
letters.index('d') # 3
letters[2:3] # ['c']
['a','b','c'] + ['d','e','f','g'] # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
                
            
                
let letters = ['a','b','c','d','e'];
letters.push('f');
letters.length; // 6
letters.includes('b'); // true
letters.indexOf('d'); // 3
letters.slice(2, 3); // ['c']
['a','b','c'] + ['d','e','f','g']; // 'a,b,cd,e,f,g' ⚠️
                
            
                
char[] letters = {'a','b','c','d','e'};
//arrays are immutable
letters.length; // 5
// other features not available in basic arrays
                
            

Array Operations

                
$letters = ['a','b','c','d','e'];
array_map(
  function ($l) { return strtoupper($l); },
  $letters
); // ['A','B','C','D','E','F']
                
            
                
letters = ['a','b','c','d','e']
[l.upper() for l in letters] # ['A','B','C','D','E','F']
                
            
                
let letters = ['a','b','c','d','e'];
letters.map(function(l) { return l.toUpperCase(); }); // ['A','B','C','D','E','F']
                
            
                
// mapping is a function of Streams
                
            

Truthiness

                
function isTruthy($var) {
    echo $var ? 'true': 'false';
}

isTruthy(true); // true
isTruthy(0); // false
isTruthy(1); // true
isTruthy('0'); // false !
isTruthy([]); // false
isTruthy([0]); // true
                
            
                
def isTruthy(var): 
    print("true" if var else "false")


isTruthy(True) # true
isTruthy(0) # false
isTruthy(1) # true
isTruthy('0') # true
isTruthy([]) # false
isTruthy([0]) # true
isTruthy({}) # false
isTruthy(set()) # false
                
            
                
function isTruthy(myVar) { 
    console.log(myVar ? 'true' : 'false')
}

isTruthy(true) // true
isTruthy(0) // false
isTruthy(1) // true
isTruthy('0') // true
isTruthy([]) // false
isTruthy([0]) // true
isTruthy({}) // true !
                
            
                
// Only booleans are truthy / falsy
                
            

Classes

                
class Vehicle {
  protected $wheels;

  public function __construct($wheels = 4) {
    $this->wheels = $wheels;
  }

  public function describe() {
    print("Has {$this->wheels} wheels\n");
  }
}


class FlyingVehicle extends Vehicle {
  protected $wings;

  public function setWings($wings) {
    $this->wings = $wings;
  }

  public function describe() {
    print("Has {$this->wheels} wheels and {$this->wings} wings\n");
  }
}


$flyingCar = new FlyingVehicle(4);
$flyingCar->setWings(2);
$flyingCar->describe();
                
            
                
class Vehicle:
  def __init__(self, wheels = 4):
    self.wheels = wheels

  def describe(self):
    print(f"Has {self.wheels} wheels")


class FlyingVehicle(Vehicle):
    def set_wings(self, wings):
    self.wings = wings

  def describe(self):
    print(f"Has {self.wheels} wheels and {self.wings} wings")


flying_car = FlyingVehicle(4)
flying_car.set_wings(2)
flying_car.describe()
                
            
                
class Vehicle {

  constructor(wheels = 4) {
    this.wheels = wheels;
  }

  describe() {
    console.log(`Has ${this.wheels} wheels`);
  }
}

class FlyingVehicle extends Vehicle {
  setWings(wings) {
    this.wings = wings;
  }

  describe() {
    console.log(`Has ${this.wheels} and ${this.wings} wings`);
  }
}


let flyingCar = new FlyingVehicle(4);
flyingCar.setWings(2);
flyingCar.describe();
                
            
                
public class Vehicle {
  protected int wheels = 4;

  public Vehicle() {
  }

  public Vehicle(int wheels) {
    this.wheels = wheels; // "this" optional
  }

  public void describe() {
    System.out.printf("Has %d wheels\n", wheels);
  }
}


public class FlyingVehicle extends Vehicle {
  protected int wings = 2;

  public void setWings(int wings) {
    this.wings = wings;
  }

  @Override
  public void describe() {
    System.out.printf("Has %d wheels and %d wings\n", wheels, wings);
  }

  public FlyingVehicle(int wheels) {
    super(wheels);
  }

  public FlyingVehicle(int wheels, int wings) {
    super(wheels);
    this.wings = wings;
  }
}


FlyingVehicle flyingCar = new FlyingVehicle(4);
flyingCar.setWings(2);
flyingCar.describe();
                
            

Single-project environments

                
# Create project (inside project dir)
composer init
# Install dependencies
composer install
# Add package
composer require [--dev] some/package
                
            
                
# Create / activate project (inside project dir)
pipenv [--three] shell
# Install dependencies
pipenv install
# Add package
pipenv install [--dev] somepackage
# Check project context
pipenv --venv
                
            
                
# Create project (inside project dir)
npm init
# Install dependencies
npm install
# Add package
npm install --save[-dev] somepackage
                
            
                
# n/a
                
            

Interactive mode / REPL

                
host$ php -a
Interactive shell

php > $x='foo';
php > var_dump($x);
string(3) "foo"
                
            
                
host$ python3
Python 3.7.2 (default, Feb 12 2019, 08:15:36)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x='foo'
>>> x
'foo'
                
            
                
host$ node --use-strict
> let x='foo'
undefined
> x
'foo'
                
            
                # Requires JDK 9+
host$ jshell
jshell> String x="foo";
x ==> "foo"
jshell> x
x ==> "foo"
                
            

Exceptions

                
try {
    throw new Exception('Boom!');
} catch (Exception $e) {
    print('Boom.');
}
                
            
                
try:
  raise Exception('Boom!')
except Exception as e:
 print('Boom.')

                
            
                
try {
  throw new Error('Boom!');
} catch (e) {
  console.log('Boom.');
}
                
            
                
try {
    throw new Exception("Boom!");
} catch (Exception e) {
    System.out.println("Boom.");
}
                
            

Notes & FAQ

What's this for?
It's a memory aid for myself for I'm working in these three languages in quick succession and can't remember the exact syntax of a given feature in one of them.
Caveat
While all code should be functional and idiomatic, it won't usually be the only way to do something in a given language. As this is not intended as an exhaustive "learn to code" resource, there are few explanations or outputs.
Java
Java is a lower-level language than the others shown here and is not directly comparable in all ways. However as my job now requires me to learn it, I'm adding it here. Note that as a result the Java code may be the least idiomatic here.
Can I use this?
Sure, but please refer to the CC BY-NC-SA 4.0 License. Note that by "non-commercial" I mean "don't sell it". If you want to use it at work or in a course, feel free, but the attribution must remain.
Can you add [Language X]?
No - I (probably) don't use it. You can fork the project for your own use though, subject to the licence.
Can you add [Feature Y]?
Possibly. Open an issue, but don't rely on a fast turnaround. Or add the feature yourself and create a pull request.
Something's incorrect
Drop me a line or open an issue or PR. The code has all been checked in a REPL but copy/paste errors can occur.
Hasn't this been done before?
So far as I'm aware, not in quite this three-way, feature-by-feature format, but Rosetta Code and 99 Bottles cover similar areas. No code from those sites has been used here, however.
Do you really use two-space tabs?
No! But adjustments have to be made to fit three languages next to each other.
Credit
This project would be far less elegant without the availability of Bootstrap and Highlight.js