Get the first element of an array

后端 未结 30 2471
醉酒成梦
醉酒成梦 2020-11-22 10:59

I have an array:

array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' )

I would like to get the first element of this array. Expect

30条回答
  •  一向
    一向 (楼主)
    2020-11-22 11:21

    I imagine the author just was looking for a way to get the first element of an array after getting it from some function (mysql_fetch_row, for example) without generating a STRICT "Only variables should be passed by reference".

    If it so, almost all the ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:

    $first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
    // or
    $first_item_of_array = reset($tmp_arr = func_get_my_huge_array());
    

    This way you don't get the STRICT message on screen, nor in logs, and you don't create any additional arrays. It works with both indexed AND associative arrays.

提交回复
热议问题