PYTHON For Each

is this article helpful?
|
Python replacement for PHP's For Each [ edit | history ]
PHP Array - Python List:
<?php
$list = array('foo', 'bar');
foreach ($list as $what) {
    echo $what.PHP_EOL;
}
?>


list = ['foo', 'bar']
for what in list:
    print what


PHP Associative Array - Python Dictionary
<?php
$arr = array('name' => 'foo', 'postion' => 'bar');
foreach ($arr as $k => $v) {
    echo 'key: ' . $k . ' - value:' . $v . '  = ' . $list[k] . "\n";
}
?>


Python 2.7 and earlier:
arr = {'name': 'foo', 'position': 'bar'}
for k,v in arr.iteritems():
    print 'key:' + k + ' - value:' + v + ' = ' + arr[k]


Python 3.0 and later (iteritems() replaced with items() ):
arr = {'name': 'foo', 'position': 'bar'}
for k,v in arr.items():
    print 'key:' + k + ' - value:' + v + ' = ' + arr[k]

PHP For Each

PHP original manual for For Each [ show | php.net ]

For Each

Starting with PHP 5, you may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In laymans terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

Example #1 For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Example #2 while() ... Next() in PHP 4

<?php 
$domainObject 
= new COM("WinNT://Domain"); 
while (
$obj $domainObject->Next()) { 
   echo 
$obj->Name "<br />"

?>

Example #3 foreach in PHP 5

<?php 
$domainObject 
= new COM("WinNT://Domain"); 
foreach (
$domainObject as $obj) { 
   echo 
$obj->Name "<br />"

?>