note 40076 added to function.in-array

From: Date: Fri, 20 Feb 2004 21:44:56 +0000
Subject: note 40076 added to function.in-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-65461@lists.php.net to get a copy of this message
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!"; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.in-array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40076 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40076&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40076&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#65461) next »