Unset array element inside a foreach loop - php

So here is my code:
<?php
$arr = array(array(2 => 5),
array(3 => 4),
array(7 => 10));
foreach ($arr as $v) {
$k = key($v);
if ($k > 5) {
// unset this element from $arr array
}
}
print_r($arr);
// now I would like to get the array without array(7 => 10) member
As you can see, I start with an array of single key => value arrays, I loop through this array and get a key of the current element (which is a single item array).
I need to unset elements of the array with key higher than 5, how could I do that? I might also need to remove elements with value less than 50 or any other condition. Basically I need to be able to get a key of the current array item which is itself an array with a single item.

foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}

It is safe in PHP to remove elements from an array while iterating over it using foreach loop:
foreach ($arr as $key => $value) {
if (key($value) > 5) {
unset($arr[$key]);
}
}

Use key() to get the first key from the sub-array.
foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}

It's not really safe to add or delete from a collection while iterating through it. How about adding the elements you want to a second array, then dumping the original?

To unset array element we Used unset() and php function like below:
foreach($array as $key=>$value)
{
if(key($value) > 5)
{
unset($array[$key]);
}
}

Related

Remove, add, move array indexes

I have a string that I converted to a multi-dimensional array.
String: 13,4,3|65,1,1|27,3,2
I wanna be able to move 27,3,2 to index 1 for example, so it would become:
13,4,3|27,3,2|65,1,1
Or remove one of those sections.
I know I can unset(), but I'm not sure how to search for an index then move it or unset it.
You can try the below one for interchanging the position of last two elements
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key] = $array[$key-1];
$array[$key-1] = $value;
}
}
This is for removing the second element.
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key-1] = $value;
unset($array[$key]);
}
}
Loop through the array using foreach
foreach($array as $key => $value)
From key you can get the key and can do whatever you like.
Other wise, you can do this if you know the key
echo $array['pass_key_name_here'];

How to create an array of arrays from another array filtering it by a specific key of the subarrays?

I have following array of arrays:
$array = [
[A,a,1,i],
[B,b,2,ii],
[C,c,3,iii],
[D,d,4,iv],
[E,e,5,v]
];
From this one, I would like to create another array where the values are extract only if the value of third key of each subarray is, for example, greater than 3.
I thought in something like that:
if $array['2'] > 3){
$new_array[] = [$array['0'],$array['2'],$array['3']];
}
So in the end we would have following new array (note that first keys of the subarrays were eliminate in the new array):
$new_array = [
[D,4,iv],
[E,5,v]
];
In general, I think it should be made with foreach, but on account of my descripted problem I have no idea how I could do this. Here is what I've tried:
foreach($array as $value){
foreach($value as $k => $v){
if($k['2'] > 3){
$new_array[] = [$v['0'], $v['2'], $v['3']];
}
}
}
But probably there's a native function of PHP that can handle it, isn't there?
Many thanks for your help!!!
Suggest you to use array_map() & array_filter(). Example:
$array = [
['A','a',1,'i'],
['B','b',2,'ii'],
['C','c',3,'iii'],
['D','d',4,'iv'],
['E','e',5,'v']
];
$newArr = array_filter(array_map(function($v){
if($v[2] > 3) return [$v[0], $v[2], $v[3]];
}, $array));
print '<pre>';
print_r($newArr);
print '</pre>';
Reference:
array_map()
array_filter()
In the first foreach, $v is the array you want to test and copy.
You want to test $v[2] and check if it match your condition.
$new_array = [];
foreach($array as $v) {
if($v[2] > 3) {
$new_array[] = [$v[0], $v[2], $v[3]];
}
}

PHP Find last key of associative multidimensional array

This is what I have tried:
foreach ($multiarr as $arr) {
foreach ($arr as $key=>$val) {
if (next($arr) === false) {
//work on last key
} else {
//work
}
}
}
After taking another look, I thinknext is being used wrong here, but I am not sure what to do about it.
Is it possible to see if I'm on the last iteration of this array?
$lastkey = array_pop(array_keys($arr));
$lastvalue = $arr[$lastkey];
If you want to use it in a loop, just compare $lastkey to $key
You will need to keep a count of iterations and check it against the length of the array you are iterating over. The default Iterator implementation in PHP does not allow you to check whether the next element is valid -- next has a void return and the api only exposes a method to check whether the current position is valid. See here http://php.net/manual/en/class.iterator.php. To implement the functionality you are thinking about you would have to implement your own iterator with a peek() or nextIsValid() method.
Try this:
foreach ($multiarr as $arr) {
$cnt=count($arr);
foreach ($arr as $key=>$val) {
if (!--$cnt) {
//work on last key
} else {
//work
}
}
}
See below url i think it help full to you:-
How to get last key in an array?
How to get last key in an array?
Update:
<?php
$array = array(
array(
'first' => 123,
'second' => 456,
'last' => 789),
array(
'first' => 123,
'second' => 456,
'last_one' => 789),
);
foreach ($array as $arr) {
end($arr); // move the internal pointer to the end of the array
$key = key($arr); // fetches the key of the element pointed to by the internal pointer
var_dump($key);
}
output:
string(4) "last" string(4) "last_one"
This function (in theory, I haven't tested it) will return the last and deepest key in a multidemnsional associative array. Give I a run, I think you'll like it.
function recursiveEndOfArrayFinder($multiarr){
$listofkeys = array_keys($multiarr);
$lastkey = end($listofkeys);
if(is_array($multiarr[$lastkey])){
recursiveEndOfArrayFinder($multiarr[$lastkey]);
}else{
return $lastkey;
}
}

Foreaching an array and matching?

How would I iterate through an array (300+ items, imported via simplexml) and pull out every item that has a certain $x->channel->item->title and put that into a different array?
I can't make heads or tails of the haystack needle thing or how to push arrays
Say I have an array (needle) like: array("3332","3300","3493","8380") and I want to match if any of those appear through the big array (haystack). How do I do this?
You have to iterate over your big array, and check for the value of $x->channel->item->title. If it meets your criteria, push it into the new array:
$theArray; // Your 300+ array
$lookFor = array('firstthing', 'second thing', 'third thing');
$newArray = array();
foreach($theArray as $x) {
if ( in_array($x->channel->item->title, $lookFor) ) {
array_push($newArray, $x);
}
}
foreach($yourArray as $key => $value)
{
//do your things with $key and/or $value
}
Modifying from Joseph's loop, you can do:
$theArray; // Your 300+ array
$newArray = array();
$matchArray = array("3332","3300","3493","8380");
foreach($theArray as $x) {
if (in_array($x->channel->item->title, $matchArray)) {
array_push($newArray, $x);
}
}
Check out in_array() at http://php.net/manual/en/function.in-array.php

php - how do I display items from an array with their values

I have this array:
Array ( [#LFC] => 1 [#cafc] => 2 [#SkySports] => 1)
How do i display it like this on a page? (preferably in value descending order as below):
\#cafc (2), #LFC (1), #SkySports (1)
Thanks
First, sort the array
arsort($arrayName);
Next, iterate througth the array keys and values.
foreach($arrayName as $key => $value)
{
echo "$key ($value),";
}
Try using arsort to sort by descending value and then looping through the array, printing key/value pairs, as follows:
arsort($original_array);
foreach($original_array as $k => $v) {
echo $k.'('.$v.')';
}
if i got your question right, use a foreach loop in combination with arsort:
arsort($array);
foreach($array as $k => $v) {
printf('%s (%s)',
htmlspecialchars($k),
htmlspecialchars($v));
}
arsort($array);
$output = array();
foreach($array as $k => $v) {
$output[] = "$k ($v)";
}
print implode(", ", $output);
this will sort the array in reverse order, then create a new array with the data formatted the way you like, then implodes the output into a string separated by commas. The other answers so far will leave a dangling comma.

Categories