开发者

Turn key-less array to associative array

开发者 https://www.devze.com 2023-01-03 03:02 出处:网络
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.

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 开发者_如何学C= '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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消