Search This Blog

PHP array() syntax into Python

Here are some comparison PHP array() into Python. In Python, there are list, dict and tuple -- or sequence in general -- as data structure format.

Example #1

PHP:
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i]."<br>";

Python:
lst = [1,2,3,4,5,6,7,8,9,10]
for item in lst:
    print str(item) + "<br>"


Example #2

PHP:
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i] = $i +1 ;

Python:
lst = range(1, 11)
for item in lst:
    print item

or...

lst = []
for i in xrange(10):
    lst.append(i + 1)
    print lst[-1]


Example #3

PHP:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}

Pyton:
lst = [1, 2, 3, 4]
lst = [val*2 for val in lst]

Example #4

PHP:
$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

Pyton:
dct = {'mot': 'one', 'hai': 'two', 'ba': 'three'}
for key, value in dct.iteritems():
    print "Key: %s; Value: %s<br />" % (key, value)


Example #5

PHP:
$arr = array("one", "two","three");
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}

Python:
lst = ['one', 'two', 'three']
for key, value in enumerate(lst):
    print "Key: %d; Value: %s<br />" % (key, value)

Example #6

PHP:
$products = array( array("ITL","INTEL","HARD"),
                        array("MIR", "MICROSOFT","SOFT"),
                        array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
                         );
for ($row = 0; $row < 3; $row++)
{
    for ($col = 0; $col <3; $col++)
    {
        echo "|".$products[$row][$col];
    }
    echo "<br>";
}

Python:
products = [['ITL', 'INTEL', 'HARD'],
    ['MIR', 'MICROSOFT', 'SOFT'],
    ['Py4C', 'pythonkhmer.wordpress.com', 'TUTORIAL']]
for product in products:
    for item in product:
        print '|' + item
    print '<br>'


PHP undoubtedly is the most popular scripting language for web development. Any thousands of web hosting companies are ready to host your application. But I prefer Django/Python, I like Python syntax style that cleaner than PHP.

Credit to intgr.

share and comment


Related Posts :