tags:

views:

30

answers:

1

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  A: 

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

Gerco Dries
Just tested this code with the spelling corrected, and it works fine.
cam8001
Thank you man! Life is hard for coder with dyslexia.
Majid
@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 ( http://php.net/manual/en/errorfunc.configuration.php )
therefromhere