我试图分割一个输入
<?php $hand = fgets(STDIN); $hand_convert = str_split($hand); print_r($hand_convert); ?>
我得到了这两个空值
C:\xampp\htdocs\coding-test\Soal 1>php search.php asd Array ( [0] => a [1] => s [2] => d [3] => [4] => )
在数组末尾有两个附加的空白值。我相信我只输入了3个单词,但它返回5个索引。这两个空白的附加值来自哪里?
我用 var_dump
var_dump
C:\xampp\htdocs\coding-test\Soal 1>php search.php asd array(5) { [0]=> string(1) "a" [1]=> string(1) "s" [2]=> string(1) "d" [3]=> " string(1) " [4]=> string(1) " " }
我试着用 array_filter 但它仍然给了我两个空白值。
array_filter
<?php $hand = fgets(STDIN); $hand_convert = str_split($hand); print_r(array_filter($hand_convert)); ?>
您可以尝试在拆分字符串之前调整值:
<?php $hand = fgets(STDIN); $hand_convert = str_split(trim($hand)); print_r($hand_convert);
还有,你的尝试 array_filter 不起作用,因为此函数删除所有空的内容,换句话说,删除所有 empty() === true . AS empty("\n") === false 它没有移除。
empty() === true
empty("\n") === false