John Garreth
John Garreth

Reputation: 1132

Get keys of an array where values is not NULL in PHP

I have an associative array in PHP

$a = array("d1" => "data", "d2" => NULL, "d3" => "data")

I want to get all keys and all values which are not NULL, in order to implode them:

// e.g.:
$sub_key    = array_keys($a, keys != NULL);
$sub_values = array_values($a, values != NULL);

echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'";

Are there functions like array_keys() and array_values() that allow to take only vales that do not match the pattern?

Upvotes: 2

Views: 9917

Answers (5)

qɐʇǝɥɐW
qɐʇǝɥɐW

Reputation: 389

$a = array("d1" => "data1", "d2" => NULL, "d3" => "data3");

$b = array_filter($a); // Not Null Values Array

$sub_key    = array_keys(array_filter($a));
$sub_values = array_values(array_filter($a));

echo "`".implode("`,`", $sub_key)."` <br/>";
echo "'".implode("','", $sub_values)."'";

Upvotes: 1

Faisal
Faisal

Reputation: 1925

Please try this:

// Loop to find empty elements and  
// unset the empty elements 
foreach($array as $key => $value)          
    if(empty($value)) 
        unset($array[$key]); 

// Display the array elements         
foreach($array as $key => $value)          
    echo ($array[$key] . "<br>"); 

In you case you will replace $array with $a. This will work for null/empty key values.

Upvotes: 1

nl-x
nl-x

Reputation: 11832

$sub_key = array();
$sub_values = array();
foreach ($a as $key => $value) {
    if (!is_null($key) && !is_null($value)) { // you can also do is_empty() in stead of is_null() if you also wan't to avoid empty string
        $sub_key[] = $key;
        $sub_values[] = $value; // or use mysql_real_escape_string($value) if you are going to create a query with this! Otherwise you will create an SQL injection vulnerability here.
    }
}

// you can add if(count($sub_key)) here to only do the echoes, if there was at least 1 item in the array. Otherwise you will echo an empty ``
echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'"; // don't you mean $sub_values here?

Upvotes: 0

Terry Harvey
Terry Harvey

Reputation: 840

You could use array_filter($a), but as one of the comments above pointed out, this would also filter out values like FALSE, empty strings, etc. So I'd use a foreach loop.

$new_array = array();

foreach ($a as $key => $value) {
    if (is_null($value) === false) {
        $new_array[$key] = $value;
    }
}

Upvotes: 2

chandresh_cool
chandresh_cool

Reputation: 11830

Use array_filter before using array_keys and filter the array like this

$newArray = array_filter($a);

Then do

$sub_key    = array_keys($newArray);
$sub_values = array_values($newArray);

Upvotes: 5

Related Questions