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

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
)

Related

Loop though array with arrays in it

I have an array with arrays in it. I need to loop through it so I have both the index as a variable, and the value as one as well.
I have run print_r($array) on my array and this is displayed:
Array
{
[ns] => Array
{
[car1]=>chevy
[car2]=>dodge
}
[mx] =>Array
{
[color1]=>red
}
}
I need the loop to display:
car1 chevy
car2 dodge
color1 red
I know I need a foreach loop but I can not seem to get it to work correctly. I always get the error:
trying to get property of non object
Below you'll find an example how to loop trough keys and values.
<?php
foreach($yourArr as $key => $value){
//$key will contain ns and mx
//$value will contain Array and Array
//So we need to loop through $value
foreach($value as $subKey => $subValue){
//$subKey will contain car1, car2 and color1
//$subValue will contain chevy, dodge, red
}
}
Going through an array of arrays to get the values of the inner arrays works like this:
foreach($array as $row => $subArray)
{
foreach($subArray as $subRow => $value)
{
echo $value . "<br/>";
}
}

PHP | Array get both value and key

I have a PHP array that looks like that:
$array = Array
(
[teamA] => Array
(
[188555] => 1
)
[teamB] => Array
(
[188560] => 0
)
[status] => Array
(
[0] => on
)
)
In the above example I can use the following code:
echo $array[teamA][188555];
to get the value 1.
The question now, is there a way to get the 188555 in similar way;
The keys teamA, teamB and status are always the same in the array. Alse both teamA and teamB arrays hold always only one record.
So is there a way to get only the key of the first element of the array teamA and teamB?
More simple:
echo key($array['teamA']);
More info
foreach($array as $key=>$value)
{
foreach($value as $k=>$v)
{
echo $k;
}
}
OR use key
echo key($array['teamA']);
echo array_keys($array['teamA'])[0];
Refer this for detailed information from official PHP site.
Use two foreach
foreach($array as $key => $value){
foreach($value as $key1 => $value2){
echo $key1;
}
}
This way, you can scale your application for future use also. If there will be more elements then also it would not break application.
You can use array_flip to exchange keys and values. So array('12345' => 'foo') becomes array('foo' => '12345').
Details about array_flip can be studied here.
I would suggest using list($key, $value) = each($array['teamA']) since the question was for both key and value. You won't be able to get the second or third value of the array without a loop though. You may have to reset the array first if you have changed its iterator in some way.
I suppose the simplest way to do this would be to use array_keys()?
So you'd do:
$teamAKey = array_shift(array_keys($array['TeamA']));
$teamBKey = array_shift(array_keys($array['TeamB']));
Obviously your approach would depend on how many times you intend to do it.
More info about array_keys and array_shift.

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;
}

Adding key=>value pair to existing array with condition

Im trying to add a key=>value to a existing array with a specific value.
Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:
ex:
[0] => Array
(
[id] => 1
[blah] => value2
)
[1] => Array
(
[id] => 1
[blah] => value2
)
I want to do it so that while
foreach ($array as $arr) {
while $arr['id']==$some_id {
$array['new_key'] .=$some value
then do a array_push
}
}
so $some_value is going to be associated with the specific id.
The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:
$tmp = new array();
foreach ($array as $arr) {
if($array['id']==$some_id) {
$tmp['new_key'] = $some_value;
}
}
array_merge($array,$tmp);
A more efficient way is this:
if(in_array($some_id,$array){
$array['new_key'] = $some_value;
}
or if its a key in the array you want to match and not the value...
if(array_key_exists($some_id,$array){
$array['new_key'] = $some_value;
}
When you use:
foreach($array as $arr){
...
}
... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:
foreach($array as &$arr){ // notice the &
...
}
... now if you add a new key to that array it will affect the $array through which you are looping.
I hope I understood your question correctly.
If i understood you correctly, this will be the solution:
foreach ($array as $arr) {
if ($arr['id'] == $some_id) {
$arr[] = $some value;
// or: $arr['key'] but when 'key' already exists it will be overwritten
}
}

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

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.)

Categories