jcadima
2/15/2017 - 10:01 PM

Filter Empty values from an array

Filter Empty values from an array




http://portfolio.planetjon.ca/2012/07/25/how-to-filter-empty-values-from-a-php-array-the-easy-way/

<?php
// grab all numbers only and add them
$input = 'bla_bla88bla.ac33titor';
$input = 'In 2017, I want to know how much does iPhone 7+ cost? and samsung *8';
$items = preg_split('/[^\d]/', $input);

print_r($items);
// will print:
Array
(
    [0] => 
    [1] => 
    [2] => 
    [3] => 2017
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
    [10] => 
    [11] => 
    [12] => 
    [13] => 
    [14] => 
    [15] => 
    [16] => 
    [17] => 
    [18] => 
    [19] => 
    [20] => 
    [21] => 
    [22] => 
    [23] => 
    [24] => 
    [25] => 
    [26] => 
    [27] => 
    [28] => 
    [29] => 
    [30] => 
    [31] => 
    [32] => 
    [33] => 
    [34] => 
    [35] => 
    [36] => 
    [37] => 
    [38] => 
    [39] => 
    [40] => 
    [41] => 7
    [42] => 
    [43] => 
    [44] => 
    [45] => 
    [46] => 
    [47] => 
    [48] => 
    [49] => 
    [50] => 
    [51] => 
    [52] => 
    [53] => 
    [54] => 
    [55] => 
    [56] => 
    [57] => 
    [58] => 
    [59] => 
    [60] => 
    [61] => 
    [62] => 8
)

// Now using  array_filter and array_values to remove the empty values

print_r( array_values(array_filter($items) ) ) ;

Array
(
    [0] => 2017
    [1] => 7
    [2] => 8
)