Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove values with digit only from array - PHP

Tags:

arrays

php

digits

I have an array like so

array(
      1=>hello,
      2=>foo,
      3=>192,
      4=>keep characters AND digits like a1e2r5,
);

All I want to do is to remove rows containing digits ONLY (3=>192), and return an array like this one :

array(
      1=>hello,
      2=>foo,
      3=>keep characters AND digits like a1e2r5,
);

I tried with array_filter but didn't get it work. Can someone show me how to do? Thanks


2 Answers

$data = array( 1 => "hello", 
               2 => "foo", 
               3 => "192", 
               4 => "keep characters AND digits like a1e2r5", 
             );

$result = array_filter( $data, 
                        function($arrayEntry) { 
                            return !is_numeric($arrayEntry);
                        }
                      );

Or using slightly more modern PHP, with arrow functions:

$result = array_filter( $data, 
                        fn($arrayEntry) => !is_numeric($arrayEntry)
                      );
like image 190
Mark Baker Avatar answered May 17 '26 08:05

Mark Baker


You could use a loop and the intval function.

$filteredArray = array();
foreach($array as $element){
    //this works because PHP is weakly typed
    if(intval($element) != $element){
        $filteredArray[] = $element;
    }
}
like image 43
rael_kid Avatar answered May 17 '26 08:05

rael_kid