Friday, April 5, 2013

PHP Array -> Iteration

Array Iteration: List all the value one by one in an array known as array iteration.

/** Example 1 - Array Iterator **/
$array = array("one", "two", "three","four");
foreach ($array  as $data) {
    echo "$data\n";
}

/** Example 2 - Array Iterator **/ 
$array1 = array("one", "two", "three","four");
while (list(, $value) = each( $array1 ) ) {
    echo "Value: $value
\n";
} 

Object Iteration: List all public variable one by one in a class. See following examples.

class TestClass{
    public $var1 = 'Val-1';
    public $var2 = 'Val-2';
    public $var3 = 'Val-3';

    protected $protected = 'Protected Var';
    private   $private   = 'Private Var';

    function testFunction() {
       echo "TestClass::testFunction:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
       
    }
}

$class = new TestClass();
foreach($class as $key => $value) {
    print "$key => $value\n";    
}

echo "\n";
$class->testFunction();

No comments:

Post a Comment