doudi2520
2018-09-26 23:28
浏览 80
已采纳

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

图片转代码服务由CSDN问答提供 功能建议

这是我的第一篇文章。 抱歉,如果我做错了...

无论如何我有一个文件通过php获取更新,这是完全正确的:

   31 
 \ N127 
 \ N131 
 \ N124 
 \ N144 
 \ N142 
 \ N133 
 \ N133 
 \ N9 
 \ N0 
 \ N22 
 \ N18 
 
 <  / code>  
 
 

我在php中创建了这个脚本:

  $ logContents = file_get_contents(“logs / mainlog.txt”); \  n $ logitemArray = explode(“
”,$ logContents); 
 
echo max($ logitemArray); 
   
 
 

但它回应9.为什么? 它在php文档中说max()应该返回数组中的最大值

提前感谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doumianfeng5065 2018-09-26 23:37
    已采纳

    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 2018-09-26 23:40

    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));
    
    打赏 评论

相关推荐 更多相似问题