PHP unsetting array in loop - php

I am trying to modify an existing array called field_data and delete the parent array of the key->value pair that has control == off. So in this example I would like to unset Array[1]. However it's not working, what am I doing wrong?
foreach ($field_data['0'] as &$subsection) {
foreach ($subsection as $key => $value)
{
if($key=='Control' && $value =='OFF')
{ echo 'match'; unset($subsection); }
}
return $field_data;
}
Field_data
----------
Array
(
[0] => Array
(
[0] => Array
(
[SECTION_ID] =>
[Control] => ON
[1] => Array
(
[SECTION_ID] =>
[Control] => OFF
)
)
)

You're trying to remove a variable that PHP is still using, specifically the array the inner loop is looping over.
The way you're checking you don't even need the inner loop. I would do something like this:
foreach( $field_data[0] as $skey => $svalue ) {
if( array_key_exists('Control', $svalue) && $svalue['Control'] == 'OFF' ) {
unset($field_data[0][$skey]);
}
}

try this...
unset($field_data[0][$subsection]);

I think you shouldn't modify array you're iterating.
Create an array of keys to remove instead, then iterate result and unset keys
$targets = array();
foreach( $field_data[0] as $skey => $svalue ) {
if( array_key_exists('Control', $svalue) && $svalue['Control'] == 'OFF' ) {
targets[] = $skey;
}
foreach($targets as $target)
{
unset($field_data[0][$target]);
}

Related

Get index from array according to a value inside

I have an array with this structure:
[items] => Array
(
[0] => items Object
(
[id:protected] => waHf9YHIEcYZAu6NmwQ9rOUZ6amsYME3
)
[1] => items Object
(
[id:protected] => waHf9YHIEcYZAu6NmwQ9rOUZ6amsYME3
)
)
Is there any way to get the index of the items according to the id:protected value? I want to unset this index based on the id value
I found a way bbut wanted to check if there is an option to not go trough all the array
foreach($items as $key => $val) {
if($val->getId() == $idIwanttodeelte) {
$index = $key;
}
}
//then unset according to index
You can remove items from an array that you are currently traversing without any issue:
foreach ($items as $key => $value) {
if ($value->getId() === $idToDelete) {
unset($items[$key]);
}
}
You could more easily use array_filter. This will create a new array without modifying the original
$filteredArray = array_filter($items, function($item) use ($idIwanttodeelte) {
return $item->getId() != $idIwanttodeelte;
});

php - How to unset array element in this condition

My array looks like this:
Array (
[0] => Array (
[value] => Array (
[source] => vimeo
[url] => https://vimeo.com/000000
)
[type] => videos
)
[2] => Array (
[value] => 62
[type] => images
)
)
I want to unset the array id with the type => images.
I tried this:
$key = array_search('images',$slides);
unset($slides[$key]);
and it only deletes the first item in the array!!!
Update:
After all, I did it this way:
foreach ( $slides as $slide => $value) {
if ($display_mode == 'images' && $value['type'] == 'videos') {
unset($slides[$slide]);
} elseif ($display_mode == 'videos' && $value['type'] == 'images') {
unset($slides[$slide]);
}
}
Thank you.
foreach ($slides as $key => $slide) {
if (in_array('images', $slide)) unset($slides[$key]);
}
array_search returns false if $needle is not found. false casts to 0 when used as an integer. You might want to consider array_filter for your use case:
$array = array(...);
$array = array_filter($array, function($item) { return in_array('images', $item); });

how to check if values exist inside a multidimensional array

i have an array like this:
Array
(
[206] => Array
(
[1] => Array
(
[formatid] => 1
[format] => CD
[formatseourl] => cd
)
)
[556] => Array
(
[] => Array
(
[formatid] =>
[format] =>
[formatseourl] =>
)
)
[413] => Array
(
[3] => Array
(
[formatid] => 3
[format] => CASETE
[formatseourl] => casete
)
)
)
...and for a specific key i want to get the values, but before i need to validate if there are values. The code is build but i dont know how to validate if there are values inside the array... ive tried isset, empty, count, array_key_exists with no success... i know im close...
$key = 556;
//if there are no formats in array, dont bother to create the ul
if (?????????formats exist in $array[$key]) { ?>
<ul><?php
foreach ($array[$key] as $value) { ?>
<li><?php echo $value['format']; ?></li><?php
} ?>
</ul><?php
} ?>
Call this function as format_exists($array[$key]) which will dig into the value to see if format isset.
function format_exists($values) {
if (!$values || !is_array($values)) return false;
$data = array_shift($values);
return $data && is_array($data) && isset($data["format"]);
}
Try this..
<?php
$key = 556;
$desiredValue = "format";
$subArray = $array[$key];
$arrayForFunction = array_pop($subArray);
if(array_key_exists($desiredValue,$arrayForFunction) && strlen($arrayForFunction[$desiredValue]))
echo "<ul><li>".$arrayForFunction[$desiredValue]."</li></ul>";
?>

After deleting the particular multidimensional array element in PHP, the Next array elements are not positioning automatically

I've created the multidimensional array in the following format
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
When I try to unset an particular array element based on id, after unset i'm getting the array like below.
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
The array element is getting unset, but the next array element doesn't move to the deleted array position.
For unset an array element, I'm using the following code.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
How to solve this issue? Please kindly help me to solve it.
Thanks in advance.
Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);
Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.
http://www.php.net/manual/en/function.array-splice.php
http://php.net/manual/en/function.unset.php
Why do you use $i++ to find an element to unset?
You can unset your element inside foreach loop:
foreach($cartdetails['products'] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);
Why don't you use this???
$id = 9;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}

Loop an array of array

in PHP, how can i loop an array of array without know if is or not an array?
Better with an example:
Array
(
[0] => Array
(
[0] => big
[1] => small
)
[1] => Array
(
[0] => big
[1] => tiny
)
[2] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[3] => row
[4] => cols
[5] => blablabla
[6] => Array
(
[0] => asd
[1] => qwe
)
}
any idea? thanks.
Which approach to choose depends on what you want to do with the data.
array_walk_recursive [docs] lets you traverse an array of arrays recursively.
You can use is_array to check if that element is an array, if it is, loop over it recursively.
You can use is_array to check if something is an array, and/or you can use is_object to check if it can be used within foreach:
foreach ($arr as $val)
{
if (is_array($val) || is_object($val))
{
foreach ($val as $subval)
{
echo $subval;
}
}
else
{
echo $val;
}
}
Another alternative is to use a RecursiveIteratorIterator:
$it = new RecursiveIteratorIterator(
new RecursiveArrayIterator($arr),
RecursiveIteratorIterator::SELF_FIRST);
foreach($it as $value)
{
# ... (each value)
}
The recursive iterator works for multiple levels in depth.
foreach( $array as $value ) {
if( is_array( $value ) ) {
foreach( $value as $innerValue ) {
// do something
}
}
}
That would work if you know it will be a maximum of 2 levels of nested array. If you don't know how many levels of nesting then you will need to use recursion. Or you can use a function such as array_walk_recursive
$big_array = array(...);
function loopy($array)
{
foreach($array as $element)
{
if(is_array($element))
{
// Keep looping -- IS AN ARRAY--
loopy($element);
}
else
{
// Do something for this element --NOT AN ARRAY--
}
}
}
loopy();

Categories