2011-12-28 22:29 阅读 38


I wonder if they disabled array_shift in > PHP 5.2.6

$realid = array_shift(explode("-", $id));

Because this code was working fine on my server PHP Version 5.2.6, while is not working in another server with higher PHP version.

If so, is there anyway I can do the following:

For a URL like this 87262-any-thing-here.html how can I get only the number, 87262, so that I will use it to call any entry from database:

$qryrec="select * from mytable where id='$realid'";
$resultrec=mysql_query($qryrec) or die($qryrec);

Is there any way to do the same without array_shift?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongyuxiao6295 dongyuxiao6295 2011-12-28 22:36


    $realid = explode("-", $id);
    $realid = $realid[0];
    点赞 评论 复制链接分享
  • donglunzai4288 donglunzai4288 2011-12-28 22:33

    Edit: To obtain the decimal value at the beginning of a string, you can use sscanf:

    $url = '87262-any-thing-here.html';
    list($realid) = sscanf($url, '%d');

    In case the URL has no decimal number at the beginning, $realid will be NULL. With explode you will get an undefined result depending on URL.

    array_shift­Docs by it's function reference needs a variable:

    enter image description here

    (see as well: Passing by Reference)

    But you give it a function:

     $realid = array_shift(explode("-", $id));

    I would not expect it to always properly work because of that. Additionally this can trigger warnings and errors on some installations.

    Instead use a variable:

     $ids = explode("-", $id);
     $realid = array_shift($ids);

    Or in your case:

     list($realid) = explode("-", $id);

    which will assing the first element of the array returned by explode to $realid. See list­Docs.

    点赞 评论 复制链接分享