Dec 6, 2016

Data structures in Python and PHP

Remember that PHP use the array language for all list, hash, set, tuple... types.

1. List

In Python, to create a list, we put a number of expressions in square brackets. In PHP we usually use the array language construct.
For example the Python code snippet:

a = ['Python', 'PHP']
is equivalent to following PHP

$a = array('Python', 'PHP');
Note that PHP 5.3 introduces declaring PHP list with using square bracket syntax:

$a = ['Python', 'PHP'];

2. Hastable

Some times called associative arrays, dictionaries, or maps. A hash is an un-ordered group of key-value pairs. The keys are usually unique strings.

In Python we use brace bracket to declare a hastable type.

a = {}
For example:

a = {1: 'hello', 'lang': 'Python'}
In PHP we declare:

$a = array(1 => 'hello', 'lang' => 'Python'); // or $a = [1 => 'hello', 'lang' => 'Python']

3. Set

We use PHP array key to represent a set item because the key is unique. For example:

$_set = array();
$_set['java'] = 1;
$_set['python'] = 2;
$_set['php'] = 3;

In Python we use curly braces to initialize set. For example:

my_set = {'java', 'python', 'php'} #since 2.7

my_set = set(['java', 'python', 'php'])

No comments:

Post a Comment