How can I delete array elements inside foreach loop? - php

I have a foreach loop and I would like to completely remove the array elements that satisfy the criteria, and change the keys to stay sequential 1,2,3,4.
I have:
$thearray = array(20,1,15,12,3,6,93);
foreach($thearray as $key => $value){
if($value < 10){
unset($thearray[$key]);
}
}
print_r($thearray);
But this keeps the keys as they were before. I want to make them 1,2,3,4, how can this be achieved?

Reset the array indices with array_values():
$thearray = array_values( $thearray);
print_r($thearray);

You can just use array_filter to remove the array elements that satisfy the criteria
$thisarray = array_filter($thearray,function($v){ return $v > 10 ;});
Then use array_values change the keys to stay 0, 1,2,3,4 .... as required
$thisarray = array_values($thisarray);

Build up a new array and then assign that to your original array after:
$thearray=array(20,1,15,12,3,6,93);
$newarray=array();
foreach($thearray as $key=>$value){
if($value>=10){
$newarray[]=$value
}
}
$thearray=$newarray;
print_r($thearray);

Related

How to merge a multidimensional array into one single dimension array

I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.
Example Array:
$nums = array (
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
What I did but get an empty array
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
Expectation
$newArr = array(1,2,3,4,5,6,7,8,9)
You could use the function array_merge() this way :
$newArr = array_merge(...$nums)
It would make your code lighter and avoid the use of a foreach loop.
array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:
$newArr = array_merge($newArr, $value);

duplicating a value inside array with using a value in another array PHP

hi i have three array like this
$arr1 = array(2,3,4,5);
$arr2 = array(1,2,3,4);
$arr3 = array();
i need a loop function to duplicate each of the value inside $arr2 with the value inside $arr1 so the end result should look like this:
$arr3= array(1,1,2,2,2,3,3,3,3,4,4,4,4,4,4);
i know that i need to do an array_push into the $arr3 with $arr2[i] by doing this
for($i=0;$i < count($arr2);$++){
array_push($arr3,$arr2[$i]);
}
but i dont know the outer loop for iterating the array_push loop, what should i add to do the duplicating?
Solution 1: You need to apply a foreach() and for() loop
1.Iterate over the first array $arr1
2.Check that value with the same key of the first array exists or not in the second array
3.Apply a loop based on first array values
4.Assign same value repeatedly based on loop
foreach($arr1 as $key=>$arr){
if(isset($arr2[$key])){
for($i=0;$i<$arr;$i++){
$arr3[] = $arr2[$key];
}
}
}
print_r($arr3);
Output:-https://eval.in/1005648
Solution 2: You can use array_merge() and array_fill()
foreach($arr1 as $key=>$arr){
$arr3= array_merge($arr3,array_fill(count($arr3),$arr,$arr2[$key]));
}
echo "<pre/>";print_r($arr3);
Output:-https://eval.in/1005666

PHP renumber array but keep sequence

I have an array like this:
array(13,4,7,1,16);
I want to recount the array, but I want to keep the sequence, like this:
array(4,2,3,1,5);
How can I do this?
If you are trying to sort the array, keeping the keys in the same order as the values, the PHP asort() function does that.
If you want to keep the original array but get the keys in sort order, then you can use something like:
$arr = array(13,4,7,1,16);
asort($arr);
$keys = array_keys($arr);
Then $keys has the keys from the original array sorted in the order of the original values, e.g. $keys = array(4,2,3,1,5);
if you want to get the index of the array with reference to the sorted values
Try this
$numbers = array(13,4,7,1,16);
$numberscopy = $numbers;
sort($numberscopy);
$final = array();
//echo array_search(13, $numbers);
for($a=0 ; $a<count($numberscopy );$a++){
$final[] = array_search($numberscopy[$a], $numbers) + 1;
}
var_dump($final);

How to remove all instances of duplicated values from an array

I know there is array_unique function, but I want to remove duplicates. Is there a built-in function or do I have to roll my own.
Example input:
banna, banna, mango, mango, apple
Expected output:
apple
You can use a combination of array_unique, array_diff_assoc and array_diff:
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
You can use
$singleOccurences = array_keys(
array_filter(
array_count_values(
array('banana', 'mango', 'banana', 'mango', 'apple' )
),
function($val) {
return $val === 1;
}
)
)
See
array_count_values — Counts all the values of an array
array_filter — Filters elements of an array using a callback function
array_keys — Return all the keys or a subset of the keys of an array
callbacks
Just write your own simple foreach loop:
$used = array();
$array = array("banna","banna","mango","mango","apple");
foreach($array as $arrayKey => $arrayValue){
if(isset($used[$arrayValue])){
unset($array[$used[$arrayValue]]);
unset($array[$arrayKey]);
}
$used[$arrayValue] = $arrayKey;
}
var_dump($array); // array(1) { [4]=> string(5) "apple" }
have fun :)
If you want to only leave values in the array that are already unique, rather than select one unique instance of each value, you will indeed have to roll your own. Built in functionality is just there to sanitise value sets, rather than filter.
You want to remove any entries that have duplicates, so that you're left with only the entries that were unique in the list?
Hmm it does sound like something you'll need to roll your own.
There is no existing function; You'll have to do this in two passes, one to count the unique values and one to extract the unique values:
$count = array();
foreach ($values as $value) {
if (array_key_exists($value, $count))
++$count[$value];
else
$count[$value] = 1;
}
$unique = array();
foreach ($count as $value => $count) {
if ($count == 1)
$unique[] = $value;
}
The answer on top looks great, but on a side note: if you ever want to eliminate duplicates but leave the first one, using array_flip twice would be a pretty simple way to do so. array_flip(array_flip(x))
Only partially relevant to this specific question - but I created this function from Gumbo's answer for multi dimensional arrays:
function get_default($array)
{
$default = array_column($array, 'default', 'id');
$array = array_diff($default, array_diff_assoc($default, array_unique($default)));
return key($array);
}
In this example, I had cached statuses and each one other than the default was 0 (the default was 1). I index the default array from the IDs, and then turn it into a string. So to be clear - the returned result of this is the ID of the default status providing it's in the same part of the multi dimensional array and not the key of it
PHP.net http://php.net/manual/en/function.array-unique.php
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
New solution:
function remove_dupes(array $array){
$ret_array = array();
foreach($array as $key => $val){
if(count(array_keys($val) > 1){
continue;
} else {
$ret_array[$key] = $val;
}
}

unsetting an array within an array

In the screenshot, you can see i have an array of arrays. I need to find an array that contains say, 'Russia', and unset it completely. That is, for Russia, remove the element [303].
I've played around with array search but I'm sure theres a funkier way of doing this.
Chris.
$array = your array;
foreach ($array as $key => $value) {
if ($value['countryName'] == 'Russia') {
unset($array[$key]);
}
}
and if you want reorder the key , you could use:
$new_array = array_values($array);

Categories