0

So I'm sure my solution is an easy one, but it just seems to escape me. I have a basic webpage where a user needs to be able to type in a beginning string of a state, hit search, and the page will output all of the states that begin with that string.

For example, if "co" was entered, then Colorado and Connecticut would be displayed, with the input case insensitive if possible. This inpt string should be able to be any length. I am using an array of $states to hold all 50 states that need to be searched. Below is what the basic form looks like.

<h1>Search States</h1>
<form method = "post" action = "states.php">
<p>Search: 

<input type="text" name="search"></p>
<p><input type = "submit" value = "Submit"></p>
</form>

  <?php

$states = array('Alabama',
'Alaska',
'Arizona',
'Arkansas',
'California',
'Colorado',
'Connecticut', etc, etc.

I assumed that some kind of regular expression search is what I am looking for, but I can't find how to produce one based off of input and using more than one character at times.

Thank you!

Ganon
  • 65
  • 8
  • Possible duplicate of [Autocomplete Textbox results based from SQL database](http://stackoverflow.com/questions/21298169/autocomplete-textbox-results-based-from-sql-database) – Spade Oct 12 '16 at 13:31

2 Answers2

1

Use this

$arr = array();
$search_str = 'Co';
foreach($states as $key => $value){
    $strlen = strlen($search_str);
    if(strtolower(substr($value, 0, $strlen)) == strtolower($search_str)){
       $arr[] = $value;
    }
}
print_r($arr);
  • 1
    Writing "use this" and the code on next line is not helpful. You should describe in brief what you are doing and how it answers the question, so that readers can learn new things instead of just copy pasting the code. – Kiran Shakya Oct 12 '16 at 14:15
0

Simply use strpos === 0:

$matches = [];

foreach ($states as $state) {
    if (strpos($state, $_POST['search']) === 0) {
        $matches[] = $state;
    }
}

It depends on you how you are going to output this information to user. Ajax, page refresh...

Justinas
  • 41,402
  • 5
  • 66
  • 96