delete 'NULL' IF it comes within a fix

0

How can I remove NULL if it comes in the array?
I was using unset() but it does not work for me.

if (in_array('NULL', $conocimientosEspecificos)) {
  unset($conocimientosEspecificos['NULL']);
}

This is my example arrangement:

array(1) {
  [0]=>
  string(4) "NULL"
}
    
asked by Carlos Enrique Gil Gil 06.04.2018 в 23:27
source

3 answers

3

You can do it in the following way:

<?php
$linksArray = ["","Hola",2,"Prueba","",NULL,0,'null'];
$linksArray = array_filter($linksArray, 'strlen');
echo '<pre>' . var_export($linksArray, true) . '</pre>';

$basura = ['null'];
$linksArray = array_diff($linksArray,$basura);
echo '<pre>' . var_export($linksArray, true) . '</pre>';
?>

If you use array_filter without passing 'strlen' when you find values bool as false or 0 you will remove them.

result 1:

array (
  1 => 'Hola',
  2 => 2,
  3 => 'Prueba',
  6 => 0,
  7 => 'null',
)

result 2:

array (
  1 => 'Hola',
  2 => 2,
  3 => 'Prueba',
  6 => 0,
)
    
answered by 06.04.2018 / 23:36
source
2

To filter strings is the same method as already explained, you only define the condition in the filtering function.

$elArray = array(0=>'NULL');
$arraysinNULLString=array_filter(
  $elArray, function($valor){
    return $valor!='NULL';
});

Note: the unset of your example does not work because it deletes the element whose key is NULL

$conocimientosEspecificos = array(
  0  => 'NULL', 
  'NULL'=>'esto se va'
);
unset($conocimientosEspecificos['NULL']);
    
answered by 06.04.2018 в 23:46
1

array_filter - Filter elements of an array

<?php

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

print_r(array_filter($entrada));
?>

result:

Array
(
    [0] => foo
    [2] => -1
)
    
answered by 06.04.2018 в 23:31