Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searching an array with class objects?

Status
Not open for further replies.

matbli

Programmer
Aug 24, 2006
3
SE
Hi,

Trying to learn PHP. Need some help with arrays.

Trying to make an array with class objects that I can search.

<?php

class Name
{
var $FirstName, $SecondName;

function __construct($FirstName, $SecondName)
{
$this->FirstName = $FirstName;
$this->SecondName = $SecondName;
}

}

$TheNames=array(Name);


$TheNames[]=new Name("FirstName1","SecondName1");
$TheNames[]=new Name("FirstName2","SecondName2");
$TheNames[]=new Name("FirstName3","SecondName3");
$TheNames[]=new Name("FirstName4","SecondName4");
$TheNames[]=new Name("FirstName5","SecondName5");
$TheNames[]=new Name("FirstName6","SecondName6");
$TheNames[]=new Name("FirstName7","SecondName7");

print_r($TheNames); // So far so good !!!! :)

$key = array_search("FirstName5", ??????????? // But her I want to search for a specific object in the array, but I dont know how to....

echo "The key".$key


?>

Maby is it not possible to do this with array_search()!?


Any help apprecierad :)

/Mats

 
Hi

Mats said:
Maby is it not possible to do this with array_search()!?
You will have to use a function which uses a callback function for matching, like [tt]array_walk()[/tt].

But as soon as you try to beautify it, you will realize that is better write your own [tt]foreach[/tt] loop.


Feherke.
 
searching inside objects and arrays is uncomfortable in php.
I would be tempted to write a search method for the Name class.

Code:
public function search ($needle){
  return in_array($needle,get_object_vars($this));
}

this is overly simplistic as it assumes a flat array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top