How do I remove the nulls out of the inner PHP array - php

I have an array from which I need to remove null values:
[227] => Array
(
[0] => 3
[1] => 8
[2] =>
[3] =>
[4] => 1
)
)
I tried array_filter($quantity);
and also
foreach ($quantity as $key => $value) {
if (is_null($value) || $value=="") {
unset($quantity);
}
}
and even tried the foreach with $quantity[0] and got Undefined offset 0. Any ideas?
UPDATE
This works but what if i dont have the 227
foreach ($quantityval[227] as $key => $value) {
if (is_null($value) || trim($value)=="") {
unset($quantityval[227][$key]);
}
}

This looks like a nested array -- your foreach statement looks correct, but needs to check the inner arrays:
foreach ($quantity as $key => $item)
foreach ($item as $key2 => $item2) {
if (is_null($item2) || $item2=="") {
unset($quantity[$key][$key2]);
}
}
}

You appear to have values that are all white-space -- either regular spaces or possibly unicode characters. Try trim($value) == "".
If that doesn't work array_filter($array, "is_integer"); may do the trick.

You updated solution works. The part about the hardcoded 227 is because $quantity is a multi-dimensional array (the extra closing parenthesis hinted that too). You need to do nested foreach for that.
foreach($bigArray as $bigKey => $smallArray)
{
foreach($smallArray as $smallKey => $value)
{
if(is_null($value) || $value == "")
unset($bigArray[$bigKey][$smallKey]);
}
}

I use something like this for situations like that:
<?php
function filter_empty_recursive($arr)
{
$keys = array_keys($arr);
foreach($keys as $key)
{
if(is_array($arr[$key]))
{
$arr[$key] = filter_empty_recursive($arr[$key]);
}
else if(empty($arr[$key]))
{
unset($arr[$key]);
}
}
return $arr;
}
It's a recursive function (so it can be a little brutal on memory with large nested array trees, and this particular one cannot handle infinite recursion (i.e.: circular reference).) But with a non-infinite recursion, and reasonably sized nested array trees, it should work pretty well. It can also be expanded to handle nested object properties as well, but that seemed outside scope. The part where it decides if it's empty is that if(empty()) so you can change that back to that is_null or empty string block.
(Edit: Adding really Low level explanation: loops through the array, if it finds an array inside of that array, it calls itself and repeats the process.)

Related

How to get every key-value-pair from PHP-array

I need to get every key-value-pair from an array in PHP. The structure is different and not plannable, for example it is possible that a key contains an additional array and so on (multidimensional array?). The function I would like to call has the task to replace a specific string from the value. The problem is that the function foreach, each, ... only use the main keys and values.
Is there existing a function that has the foreach-function with every key/value?
There is not a built in function that works as you expect but you can adapt it using the RecursiveIteratorIterator, walking recursively the multidimensional array, and with the flag RecursiveIteratorIterator::SELF_FIRST, you would get all the elements of the same level first, before going deeper, not missing any pair.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $item) {
// LOGIC
}
The usual approach to this kind of task is using a recursive funcion.
Let's go step by step:
First you need the foreach control statement...
http://php.net/manual/en/control-structures.foreach.php
..that let you parse the associative array without knowing keys' names beforehand.
Then is_array and is_string (and eventually is_object, is_integer...) let you check the type of each value so you can act properly.
http://php.net/manual/en/function.is-array.php
http://php.net/manual/en/function.is-string.php
If you find the string to be operated then you do the replace task
If you find an array the function recalls itself passing the array just parsed.
This way the original array will be parsed down to the deepest level without missing and key-value pair.
Example:
function findAndReplaceStringInArray( $theArray )
{
foreach ( $theArray as $key => $value)
{
if( is_string( $theArray[ $key ] )
{
// the value is a string
// do your job...
// Example:
// Replace 'John' with 'Mike' if the `key` is 'name'
if( $key == 'name' && $theArray[ $key ] == "John" )
{
$theArray[ $key ] = "Mike";
}
}
else if( is_array( $theArray[ $key ] )
{
// treat the value as a nested array
$nestedArray = $theArray[ $key ];
findAndReplaceStringInArray( $nestedArray );
}
}
}
You can create a recursive function to treat it.
function sweep_array(array $array)
{
foreach($array as $key => $value){
if(is_array($value))
{
sweep_array($value);
}
else
{
echo $key . " => " . $value . "<br>";
}
}
}

PHP Array reference, modifying array values

I'm trying to modify an array when looping through it and increment certain values.
$data = ['traits' => [[['amt' => 1]]]];
var_dump($data['traits']);
foreach ($data['traits'] as $key => &$index) {
foreach ($index as $key => &$value) {
$value['amt'] = $value['amt']++; // This should increment
if (in_array($key, $input)) {
$i++;
$insert["field_".$i] = $key."_1";
}
}
}
var_dump($data['traits']); // SAME AS PREVIOUS VAR_DUMP
What you are doing in the loop is undefined:
$value['amt'] = $value['amt']++;
The outcome of that depends on what's evaluated first. In this case $value['amt']++ seems to be evaluated first and then assigned to $value['amt'] again; the side effect of the increment is lost.
On the other hand, the following statement will work as expected:
$value['amt']++;

how to loop though an array and unset variables in the array

is there a way to loop through an array and unset any variables that are =""?
i am looking for a faster way to do this aside form writing 4 if else statements.i thought this might work but i don't know if it can be done this way or not.
$a=""
$b="123"
$c=""
$d"123"
$var=array($a,$b,$c,$d)
i am trying to loop through $var array to get
$var= array($b,$d)
is this even possible or should i stick with writing 4 if else statements?
Have a look here : How to delete object from array inside foreach loop?
or here :
How do you remove an array element in a foreach loop?
foreach ($array as $key => $value) {
if($value == "") {
unset($array[$key]);
}
}
Good luck
$x=["","123","","345"];
$var = array_filter($x);
print_r($var);
The result:
Array
(
[1] => 123
[3] => 345
)

foreach and multidimensional array

I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:
$main_array = array
(
[first_array] => array
(
['first_array1'] => product1
['first_arrayN'] => productN
)
[nth_array] => Array
(
[nth_array1] => date1
[nth_arrayN] => dateN
)
)
function getresult($something){
## some code
};
foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
$result["{$X_array}"]["{$key}"] = getresult($value);
echo $result["{$X_array}"]["{$key}"];
};
Any help would be appreciated!
foreach ($main_array as &$inner_array) {
foreach ($inner_array as &$value) {
$value = getresult($value);
echo $value;
}
}
unset($inner_array, $value);
Note the &, which makes the variable a reference and makes modifications reflect in the original array.
Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.
foreach($main_array AS $key=>$array){
foreach($array AS $newKey=>$val){
$array[$newKey] = getResult($val);
}
$main_array[$key] = $array;
}

PHP Get all numerical/anonymous keys in an array

I have a multidimensional array, I am interested in getting all the elements (one level deep) that don't have named keys.
i.e.
Array
{
['settings'] {...}
['something'] {...}
[0] {...} // I want this one
['something_else'] {...}
[1] {...} // And this one
}
Any ideas? Thanks for your help.
This is one way
foreach (array_keys($array) as $key) {
if(is_int($key)) {
//do something
}
}
EDIT
Depending on the size of your array it may be faster and more memory efficient to do this instead. It does however require that the keys are in order and none are missing.
for($i=0;isset($array[$i]);$i++){
//do something
}
$result = array();
foreach ($initial_array as $key => $value)
if ( ! is_string( $key ) )
$result[ $key ] = $value;
The key is 0, Shouldn't be $your_array[0]?

Categories