0

The following code outputs would where we expect it to output 12/5/10. The reason is array_search only works on associative arrays and explode returns a key-less array, so $k is false and $k+1 is 1.

$s = 'We would like to book a double room form 12/5/10 for three nights.';
$s_arr = explode(' ', $s);
$k = array_search('from', $s_arr);
$from = $s_arr[$k+1];
echo $from;

We can verify this by using a literal definition like this

$s_arr = array(
  0 => 'We',
  1 => 'would',
  2 => 'like',
  3 => 'to',
  4 => 'book',
  5 => 'a',
  6 => 'double',
  7 => 'room',
  8 => 'form',
  9 => '12/5/10',
  10=> 'for',
  11=> 'three',
  12=> 'nights.');
$k = array_search('from', $s_arr);
$from = $s_arr[$k+1];
echo $from;

This time the correct value is out which is 12/5/10.

Is there a way to turn a key-less array to an associative one?

4
  • Just tried the second code block, it fails too! What am I missing? Commented Jun 13, 2010 at 16:17
  • 1
    Why are you doing this at all? It seems the purpose of this function is to extract the date. If so, it would make sense to use a regular expression. preg_match is way faster for these things than your array explode roundtrip and array_search. Commented Jun 13, 2010 at 17:23
  • @mario - these are beginning steps to implement an intelligent responder. A lot will be changed, but for now explode+search would do. Commented Jun 13, 2010 at 17:30
  • You know, that's a difficult undertaking! ;] Natural language parsers/responders aren't easy. But especially since you've already run into one misspelling, you should take the regex route. It's way more reliable and shorter. preg_match("#[from]{2,6}\s*(\d+/\d+/\d+)#", $s, $match) for catching your date. Works for misspellings like frm, fromm, form, frrom, etc.. Easier. Come over to the dark side. Commented Jun 13, 2010 at 18:49

1 Answer 1

4

I would say it does this because you misspelled "from" in the original string you are exploding.

Sign up to request clarification or add additional context in comments.

2 Comments

Just tested this code with the spelling corrected, and it works fine.
@Majid - I recommend using Netbeans or some other IDE - that should make it easier to identify typos like this. Also, set error logging to include E_NOTICE and keep an eye on the error log ( php.net/manual/en/errorfunc.configuration.php )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.