Welcome Guest, Not a member yet? Register   Sign In
Better way to find a value in an object?
#1

[eluser]chefnelone[/eluser]
Hello,

I'm using this code to look for a given matches in an object. I works fine but it needs to loop the whole object.
Is there a better way to do this? Anyway to skip the foreach()?
Code:
$area = 'My area';
foreach($seccion as $seccion_data){
    if($seccion_data->area == $area){
            echo $seccion_data->name;
         }
}
#2

[eluser]sooner[/eluser]
again loop through the $seccion_data..like foreach($seccion_data as $somename)
#3

[eluser]chefnelone[/eluser]
[quote author="sooner" date="1294184954"]again loop through the $seccion_data..like foreach($seccion_data as $somename)[/quote]

What ?
#4

[eluser]sooner[/eluser]
i did not get your question last time.
#5

[eluser]dudeami0[/eluser]
Using a break will allow you to stop looping once you get what you want.
#6

[eluser]chefnelone[/eluser]
[quote author="dudeami0" date="1294196892"]Using a break will allow you to stop looping once you get what you want.[/quote]
Nice one, but what if you have more than one match?
#7

[eluser]dudeami0[/eluser]
You could wrap it in a condition, like:

Code:
$area = 'My area';
$matches = 0;
foreach($seccion as $seccion_data){
    if($seccion_data->area == $area){
        echo $seccion_data->name;
        ++$matches;
        if ($matches >= 5)
            break;
    }
}

Btw, where is this array coming from? That might help with making a more efficient way of getting the results you want.
#8

[eluser]chefnelone[/eluser]
[quote author="dudeami0" date="1294198449"]You could wrap it in a condition, like:

Code:
$area = 'My area';
$matches = 0;
foreach($seccion as $seccion_data){
    if($seccion_data->area == $area){
        echo $seccion_data->name;
        ++$matches;
        if ($matches >= 5)
            break;
    }
}

Btw, where is this array coming from? That might help with making a more efficient way of getting the results you want.[/quote]

but this just break the foreach when it find 5 matches....?¿

I'm looking fordward for a different thing, I just want to know how to get ride of the foreach() so that there is no need to loop the complete object...
#9

[eluser]dudeami0[/eluser]
You have too loop through the array to compare objects in the array. You'd have to store your information in a way where you don't need too search through and array, such as a MySQL database.




Theme © iAndrew 2016 - Forum software by © MyBB