获取索引,同时将元素插入到php数字索引数组中

时间:2014-08-01 04:21:53

标签: php arrays

示例代码就像这里一样。

<?php

   $new_room_result = array();
   $rooms = array('single room' , 'delux room' , 'president room' , 'seavie room');

   foreach($rooms as $room){

     $new_room_result[] = $room;
     // the next step - i want to get the index of after last inserment's index.

   }

?> 

有没有人有任何想法?

3 个答案:

答案 0 :(得分:1)

 foreach($rooms as $room){

   $new_room_result[] = $room;
  end($new_room_result);         // move the internal pointer to the end of the array
  $key = key($new_room_result);
      var_dump($key);

 }

答案 1 :(得分:1)

我通过array_keys()和array_pop()函数找到它。 是否有更简单的方法来达到我想要的目的。

答案 2 :(得分:0)

您需要做的就是获得数组的长度:

$index = count($new_room_result);

插入后,进入$ new_room_result,其内容将是

array (size=4)
  0 => string 'single room' (length=11)
  1 => string 'delux room' (length=10)
  2 => string 'president room' (length=14)
  3 => string 'seavie room' (length=11)

最后一个索引是3,后面的索引是4,这是数组的大小