0

I tried to split an input

<?php
$hand = fgets(STDIN);
$hand_convert = str_split($hand);
print_r($hand_convert);
?>

I got this two blank value

C:\xampp\htdocs\coding-test\Soal 1>php search.php
asd
Array
(
    [0] => a
    [1] => s
    [2] => d
    [3] =>
    [4] =>

)

There is two added blank value at the end of array. I believe that i just enter 3 word, but it return 5 index. Where the two blank value add came from ?

i got this type of data using 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) "
"
}

I tried to remove it using array_filter but it still gave me the two blank values.

<?php
$hand = fgets(STDIN);
$hand_convert = str_split($hand);
print_r(array_filter($hand_convert));
?>
Gagantous
  • 432
  • 6
  • 29
  • 69

1 Answers1

1

You could try trimming your value before you split the string:

<?php
$hand = fgets(STDIN);
$hand_convert = str_split(trim($hand));
print_r($hand_convert);

Also, your attempt with array_filter did not work because this function removes everything that is empty, in other words, everything that empty() === true. As empty("\n") === false it did not remove.

thyago stall
  • 1,654
  • 3
  • 16
  • 30