• Home
  • Blog
  • Demos
  • About
  • ------------------
  • Articles
  • Csharp(59)
    • controls (4)
    • methods (5)
    • tutorials (50)
  • Html(1)
    • tutorials (1)
  • Java(10)
    • mobile (10)
  • Javascript(5)
    • tutorials (5)
  • Linux(3)
    • tutorial (3)
  • Math(10)
    • tutorials (10)
  • Php(15)
    • functions (1)
    • mysql (6)
    • tutorials (8)
  • Sql(23)
    • tutorials (23)
  • Vba(1)
    • tutorials (1)

How to loop through an array of objects

Written: 2010-02-05 06:55:54
Mood: Happy
Subject: programming
Working mostly object oriented in PHP I just realized I needed to loop through an array of objects. It turned out that it worked pretty much as it should do:

Code


<?php
class Person{
//Fields
private $name;
private $age;
private $id;

//Properties
public function getName() { return $this->name; }
public function getAge() { return $this->age; }
public function getId() { return $this->id; }

public function setName($name) { $this->name = $name; }
public function setAge($age) { $this->age = $age; }
public function setId($id) { $this->id = $id; }

//Construct
public function __construct($name, $age){
$this->setName($name);
$this->setAge($age);
}
}

//=================Run program========================

//Create some people
$p1 = new Person("John", 45);
$p2 = new Person("Lisa", 34);
$p3 = new Person("Jake", 12);

//Create an array of Person objects
$people = array($p1, $p2, $p3);

//Output the objects in the array
for($i = 0; $i < sizeof($people); $i++){
if(is_object($people[$i])){
$people[$i]->setId($i + 1);
}
else {
echo "Error at loop index ".$i."<br />";
echo "<pre>";
echo var_dump($people[$i]);
echo "</pre>";
}
}

echo "<pre>";
print_r($people);
echo "</pre>";
?>


Output


Array
(
[0] => Person Object
(
[name:private] => John
[age:private] => 45
[id:private] => 1
)

[1] => Person Object
(
[name:private] => Lisa
[age:private] => 34
[id:private] => 2
)

[2] => Person Object
(
[name:private] => Jake
[age:private] => 12
[id:private] => 3
)

)