1

I have a problem with the deleting of next line empty data using laravel. Where did I go wrong?

I tried using this code explode, str_replace and array_map but still i don't get want i want.

$string = str_replace(array("\r", "\n"), "\n", $tempData[0]);
$your_arrays = array_map("trim", explode("\n", $string));

print_r ($your_arrays);

Array
(
    [0] => 
    [1] => 
    [2] => Sample Text1
    [3] => 
    [4] => Sample text 2
    [5] => Sample Text 3
    [6] => 
    [7] => 
    [8] => Sample Text 4
    [9] => Sample Text 5
    [10] => Sample Text 6
    [11] => Sample Text 7
    [12] => Sample Text 8
    [13] => 
    [14] => 
    [15] => 
)

I'm expecting the result with this

Array
(
    [1] => Sample Text1
    [2] => Sample text 2
    [3] => Sample Text 3
    [4] => Sample Text 4
    [5] => Sample Text 5
    [6] => Sample Text 6
    [7] => Sample Text 7
    [8] => Sample Text 8
)
Jitendra Ahuja
  • 749
  • 3
  • 9
  • 22
Jelbert
  • 57
  • 8

4 Answers4

3

use array_filter to remove all

2

You can use array_filter to remove all the empty entries in an array.

melvin
  • 2,571
  • 1
  • 14
  • 37
2

You can use array_filter() function.

    $var = array(
       0 => 'foo',
       1 => false,
       2 => -1,
       3 => null,
       4 => ''
   );

    print_r(array_filter($var));
Serhat Canat
  • 66
  • 1
  • 3
  • 3
    Hello! Better to link the english version of the manual. Careful that, according to [php boolean conversion](https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting) also a string equal to '0' is considered false and removed by `array_filter()` without a callback, may not be what the OP wants. May be better to define a proper callback. – Valentino Apr 18 '19 at 09:17
  • 1
    All entries of array equal to FALSE [bool conversion](https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback – Jitendra Ahuja Apr 18 '19 at 09:21
0

You can simply use array_filter(), which conveniently handles all this for you:

print_r(array_filter($Your_Array));

Jitendra Ahuja
  • 749
  • 3
  • 9
  • 22