doudi2520
doudi2520
2018-09-26 23:28

php max函数从数组返回最小值

已采纳

this is my first post. sorry if i did something wrong...

anyways i have a file that gets updates by php and this is EXACTLY it:

31

127

131

124

144

142

133

133

9

0

22

18

i made this script in php:

$logContents = file_get_contents("logs/mainlog.txt");
$logitemArray = explode("
", $logContents);

echo max($logitemArray);

but it echos 9. why? it said in the php documentation that max() should return the biggest value in the array

thanks in advance

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

2条回答

  • doumianfeng5065 doumianfeng5065 3年前

    explode() returns an array of strings, so they're being compared lexicographically. You need to convert them to numbers so that max() will compare them numerically.

    $logitemArray = array_map('intval', explode("
    ", $logContents));
    echo max($logitemArray);
    

    BTW, you can use the file() function to read a file directly into an array of lines, instead of using file_get_contents() followed by explode().

    $logitemArray = array_map('intval', file("logs/mainlog.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    
    点赞 评论 复制链接分享
  • duan02468 duan02468 3年前

    Like the comments have said, it's because 9 is the largest lexigraphical value. If it said 900 it would still be the same.

    This is because when you split the string with explode you get an array of type string. The following code will convert the elements in the array to integers which should give expected behaviour.

    $logitemArray = array_map('intval', explode("
    ", $logContents));
    
    点赞 评论 复制链接分享

为你推荐