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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.