note 40076 deleted from function.in-array by irchtml

From: Date: Wed, 25 Feb 2004 20:00:15 +0000
Subject: note 40076 deleted from function.in-array by irchtml
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-65751@lists.php.net to get a copy of this message
Note Submitter: sean@natoewal.nl ---- For searching an object in array I made the ObjectArray class. An instance of this class is an array which contains the objects as strings which makes searching for objects possible. <?php class ObjectArray { var $objectArray = array(); function ObjectArray() { } function inArray($object) { $needle = $this->object2String($object); return in_array($needle, $this->objectArray); } function object2String($object) { $str = ""; $vars = get_object_vars($object); foreach ($vars as $value) $str .= (is_object($value)) ? $this->object2String($value) : $value; return $str; } function addObject($object) { $str = ""; $vars = get_object_vars($object); foreach ($vars as $value) $str .= $value; array_push($this->objectArray, $str); } } ?> You can use this class like: <?php $objectArray = new ObjectArray(); $myFirstCar = new Car("brown", 20); $objectArray->addObject($myFirstCar); $mySecondCar = new Car("red", 160); $objectArray->addObject($mySecondCar); ?> This example uses the Car class: <?php class Car { var $color; var $speed; function Car($color, $speed) { $this->color = $color; $this->speed = $speed; } } ?> The next code shows an example if we were searching for my first car: <?php if ($objectArray->inArray($myFirstCar)) { echo "I've found your first car!"; } ?>

« previous php.notes (#65751) next »