Jump to content

Search in Array


iceblox

Recommended Posts

Hi all,

 

I have an array which is structured like so;

 

$arr[] = "'Model'=>Samsung M110,'Text'=>The text of the blah blah...,'ID'=>1";

 

and there are loads of rows of these obviously.

 

What im trying to do is pass in a search term ie. "Samsung M110" or "M110" I want to be able to search the array and then return the intire row if something matches, so that i can echo it out.

 

I have tried numerous things but cant seem to find the code that i need to get this to work.

 

Does anyone i have any ideas?

 

Thanks,

Link to comment
https://forums.phpfreaks.com/topic/176578-search-in-array/
Share on other sites

You could use a loop to go through all entries and store the found match in a variable. You could use a regular expression to check if a value is in it.

something like:

<?php
$search = "M110";
$match;
foreach($arr as $item){
  if(your_regex_func($search,$item)){
    $match = $item;
    break;
  }
}

 

edit needed the search param too other then that strstr  and stristr are probably better for this then a regex

Link to comment
https://forums.phpfreaks.com/topic/176578-search-in-array/#findComment-930894
Share on other sites

So it should look something like this?

 

 

function search_func($search,$item)
{
return strstr($item,$search);
}
$search = "Nokia N95";
$match;
foreach($arr as $item){
  if(search_func($search,$item)){
    $match = $item;
break;
  }
}

 

Once this works will I then be able to find which ones matched?

Link to comment
https://forums.phpfreaks.com/topic/176578-search-in-array/#findComment-930924
Share on other sites

Hmmm re-reading the way you had written the first array It awfully looks a lot like a database record. If this is so  you're better of using a query instead of doing it with PHP.

 

If it's just a multidimentional array then you should use a a double loop checking for all the fields.

 

Link to comment
https://forums.phpfreaks.com/topic/176578-search-in-array/#findComment-930998
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.