note 40079 deleted from function.in-array by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: sean at natoewal dot 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 = $this->object2String($object);  
        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!";
}
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.