How to remove empty and null values from an array in php? - php

I want to remove the empty and null values from $listValues array.
Here I am removed the empty values using array_filter.
Sample Code:
$listValues = array("one", "two", "null","three","","four","null");
$resultValues = array_filter($listValues);
echo "<pre>";
print_r($resultValues);
echo "</pre>";
Result:
Array ( [0] => one [1] => two [2] => null [3] => three [5] => four [6] => null )
But I want
Array ( [0] => one [1] => two [3] => three [5] => four )
Any advice greatly appreciated.

try this : use array_diff() function compares the values of two (or more) arrays, and returns the differences. to remove null and "" . if you need to remove some more field then add that values inside the array
<?php
$listValues = array("one", "two", "null","three","","four","null");
echo "<pre>";
$a=array_values(array_diff($listValues,array("null","")));
print_r($a);
echo "</pre>";
?>
output :
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
refer
http://www.w3schools.com/php/func_array_diff.asp

Try array_filter with second parameter as a user defined function like this:
$listValues = array("one", "two", "null","three","","four","null");
print_r(array_filter($listValues, "filter"));
function filter($elmnt) {
if ($elmnt != "null" && $elmnt != "" ) {
return $elmnt;
}
}

Use this code, First I corrected the index of an array, then unset null values from an array then corrected array indexes again:
$listValues = array("one", "two", "null","three","","four","null");
$listValues = array_values($listValues);
$temp = $listValues;
for($loop=0; $loop<count($listValues); $loop++){
if($listValues[$loop] == "" || $listValues[$loop] == "null"){
unset($temp[$loop]);
}
}
$listValues = $temp;
$listValues = array_values($listValues);
echo "<pre>";
print_r($listValues);
echo "</pre>"; die;
But, if you want same indexes to get this output:
Array ( [0] => one [1] => two [3] => three [5] => four )
Then don't use this before <pre>:
$listValues = array_values($listValues);

Related

How to get value of array based on matching on key

Hi i am working on some operations where i need to get value of array from its key.
I have $attr_color variable with the value red.
So if red is in the array then it needs to be return its value.
Below is my array :
Array
(
[0] => Array
(
[label] =>
[value] =>
)
[1] => Array
(
[label] => red
[value] => 32
)
[2] => Array
(
[label] => green
[value] => 33
)
[3] => Array
(
[label] => pink
[value] => 34
)
[4] => Array
(
[label] => black
[value] => 35
)
[5] => Array
(
[label] => white
[value] => 36
)
)
I have tried below code but it returns blank :
$attr_color = "red";
//$response is my array which i have mention above.
if(in_array($attr_color,array_column($response,"label")))
{
$value = $response['value'];
echo "Value".$value;
exit;
}
Help ? where i made mistake ?
Use array_search, and check for false:
$index = array_search($attr_color, array_column($response,"label"));
if ($index !== false) {
echo $response[$index]['value'];
}
In your case it's enough to use a regular foreach loop:
$attr_color = "red";
$value = "";
foreach ($response as $item) {
if ($item['label'] == $attr_color) {
$value = $item['value'];
break; // avoids redundant iterations
}
}
Try this simple solution, hope this will help you out. Here we are using array_column for getting columns and indexing it with keys and values, Where keys are labels and values as value
Try this code snippet (with sample inputs)
$result=array_column($array, 'value',"label");
$result=array_filter($result);
echo $result["red"];
By using array_column with third parameter and array_search as
$attr_color="red";
$arr = array_filter(array_column($response, "label", 'value'));// pass thired parameter to make its key
if (array_search($attr_color, $arr)) {// use array search here
echo array_search($attr_color, $arr);
}
Try below code : using array match function :
$your_value = array_search($attr_color, array_column($response,"label"));
if ($index !== false) {
echo $response[$your_value]['value'];
}
Try:
$attr_color = "red";
//$response is my array which i have mention above.
$index = array_search($attr_color, array_column($response, 'label'));
if($index!==false){
$value = $response[$index]['value'];
echo "Value:".$value;
exit;
}
Here $index will get the index of the array with label red
Use array_search instead of in_array
$attr_color = "red";
if(($index = array_search($attr_color,array_column($response,"label")))!==FALSE)
{
$value = $response[$index]['value'];
echo "Value".$value;
exit;
}

How do I get value of specific array element by secondary key?

This has to be easy but I am struggling with it. If the array below exists (named "$startersnames") and I specifically want to echo the value that has "qb" as the key, how do I do that?
I assumed $startersnames['qb'], but no luck.
$startersnames[0]['qb'] works, but I won't know that it's index 0.
Array
(
[0] => Array
(
[qb] => Tannehill
)
[1] => Array
(
[rb] => Ingram
)
[2] => Array
(
[wr] => Evans
)
[3] => Array
(
[wr] => Hopkins
)
[4] => Array
(
[wr] => Watkins
)
[5] => Array
(
[te] => Graham
)
[6] => Array
(
[pk] => Hauschka
)
[7] => Array
(
[def] => Rams
)
[8] => Array
(
[flex] => Smith
)
)
You can use array_column (from php 5.5) like this:
$qb = array_column($startersnames, 'qb');
echo $qb[0];
Demo: http://3v4l.org/QqRuK
This approach is particularly useful when you need to print all the wr names, which are more than one. You can simply iterate like this:
foreach(array_column($startersnames, 'wr') as $wr) {
echo $wr, "\n";
}
You seem to be expecting an array with text keys and value for each, but the array you have shown is an array of arrays: i.e. each numeric key has a value which is an array - the key/value pair where you are looking for the key 'qb'.
If you want to find a value at $array['qb'] then your array would look more like:
$array = [
'qb' => 'Tannehill',
'rb' => 'etc'
];
now $array['qb'] has a value.
If the array you are inspecting is a list of key/value pairs, then you have to iterate over the array members and examine each (i.e. the foreach loop shown in your first answer).
For your multi-dim array, you can loop through the outer array and test the inner array for your key.
function findKey(&$arr, $key) {
foreach($arr as $innerArr){
if(isset($innerArr[$key])) {
return $innerArr[$key];
}
}
return ""; // Not found
}
echo findKey($startersnames, "qb");
You can try foreach loop
$key = "qb";
foreach($startersnames as $innerArr){
if(isset($innerArr[$key])) {
echo $innerArr[$key];
}
}
$keyNeeded = 'qb';
$indexNeeded = null;
$valueNeeded = null;
foreach($startersnames as $index => $innerArr){
//Compare key
if(key($innerArray) === $keyNeeded){
//Get value
$valueNeeded = $innerArr[key($innerArray)];
//Store index found
$indexNeeded = $index;
//Ok, I'm found, let's go!
break;
}
}
if(!empty($indexNeeded) && !empty($valueNeeded)){
echo 'This is your value: ';
echo $startersnames[$indexNeeded]['qb'];
echo 'Or: ':
echo $valueNeeded;
}
http://php.net/manual/en/function.key.php

Comparing two arrays with array_diff

I have the following code and am trying to compare two array's with array_diff however I keep getting no results. I not sure if it matters, but there are many fields in the array and I really only want to compare 1 field...is this possible? what am I missing?
<?php
$json = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-AZ&back=7&fmt=json");
$json2 = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-NV&back=7&fmt=json");
$array1 = json_decode($json, TRUE);
$array2 = json_decode($json2, TRUE);
if ( $array1 == $array2 ) {
echo 'There are no differences';
}else
var_dump(array_diff($array2, $array1));
echo 'they are different';
?>
You will need to check the arrays against each other:
$Array_1 = array (1,2,3,4,5);
$Array_2 = array(1,2,3,4,5,6);
print_r(array_diff($Array_1,$Array_2));
Will output:
Array
(
)
Whereas:
print_r(array_diff($Array_2,$Array_1));
will output:
Array
(
[5] => 6
)
So this might be a solution:
function ArrayDiff ($Array_1, $Array_2){
$Compare_1_To_2 = array_diff($Array_1,$Array_2);
$Compare_2_To_1 = array_diff($Array_2,$Array_1);
$Difference_Array = array_merge($Compare_1_To_2,$Compare_2_To_1);
return $Difference_Array;
}
print_r(ArrayDiff($Array_1,$Array_2));
Which will output:
Array
(
[0] => 6
)
Putting this into an if statement:
$Differences = ArrayDiff($Array_2,$Array_1);
if (count($Differences) > 0){
echo 'There Are Differences Between The Array:';
foreach ($Differences AS $Different){
echo "<br>".$Different;
}
All the examples and code is based off the arrays at the start ($Array_1 and $Array_2)
$po_line_array=array();
$po_line_clone_array=array();
foreach($cart->line_items as $line_no => $po_line)
$po_line_array[$line_no]=$po_line->labdip_details_id;
print_r($po_line_array,1);
foreach($cart->line_items_clone as $line_no_clone => $po_line_clone)
$po_line_clone_array[$line_no_clone]=$po_line_clone->labdip_details_id;
print_r($po_line_clone_array,1);
$result=array_diff($po_line_clone_array,$po_line_array);
print_r($result,1);
Output:
Array ( [0] => 101 )
Array ( [0] => 101 [1] => 103 )
Array ( [1] => 103 )

Array formatting into a specific format?

I am getting an array like below after i formatted my result set into the below format.
Array
(
[0] => xxx#2456
[1] => xxx#2345
[2] => xxy#1234
[3] => xxy#123
[4] => xyz#3456
);
I want the result array from the above array like below. I am thinking how ot proceed using PHP string functions or is there any other way.
Note: There may be so many array elements like the above but i want unique elements after we added last digits after '#'.
Array
(
[0] => xxx#4801
[1] => xxy#1464
[2] => xyz#3456
);
Any ideas how to proceed....... In the above output array format xxx#4801 is sum of 2345 and 2456 of Input array.......
You can try
$unique = array_reduce($data, function ($a, $b) {
$c = explode("#", $b);
if (isset($a[$c[0]])) {
$d = explode("#", $a[$c[0]]);
$a[$c[0]] = $c[0] . "#" . ($c[1] + $d[1]);
} else {
$a[$c[0]] = $b;
}
return $a;
}, array());
echo "<pre>";
print_r(array_values($unique));
Output
Array
(
[0] => xxx#4801
[1] => xxy#1357
[2] => xyz#3456
)
Simple Online Demo
You can use array_unique() function and reindex it with array_values() Find the code for example.
array_unique($array)
array_values(array_unique($array));

Can't remove empty elements from array

I want to remove empty elements from an array. I have a $_POST-String which is set to an array by explode(). Then I'am using a loop to remove the empty elements. But that does not work. I also tried array_filter(), but with no succes. Can you help me? See Code below:
$cluster = explode("\n", $_POST[$nr]);
print_r ($cluster);
echo "<br>";
for ($i=0 ; $i<=count($cluster);$i++)
{
if ($cluster[$i] == '')
{
unset ( $cluster[$i] );
}
}
print_r ($cluster);
echo "<br>";
Result:
Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => [5] => )
Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => )
Empty elements can easily be removed with array_filter:
$array = array_filter($array);
Example:
$array = array('item_1' => 'hello', 'item_2' => '', 'item_3' => 'world', 'item_4' => '');
$array = array_filter($array);
/*
Array
(
[item_1] => hello
[item_3] => world
)
*/
The problem ist that the for loop condition gets evaluated on every run.
That means count(...) will be called multiple times and every time the array shrinks.
The correct way to do this is:
$test = explode("/","this/is/example///");
print_r($test);
$arrayElements = count($test);
for($i=0;$i<$arrayElements;$i++)
if(empty($test[$i])
unset($test[$i]);
print_r($test);
An alternative way without an extra variable would be counting backwards:
$test = explode("/","this/is/example///");
print_r($test);
for($i=count($test)-1;$i>=0;$i--)
if(empty($test[$i])
unset($test[$i]);
print_r($test);
What if you change:
for ($i=0 ; $i<=count($cluster);$i++) { if ($cluster[$i] == '') { unset ( $cluster[$i] ); } }
to
for ($i=0 ; $i<=count($cluster);$i++) { if (trim($cluster[$i]) == '') { unset ( $cluster[$i] ); } }

Categories