I built this function in PHP so far called removeAllValuesMatching, but I cannot seem to get it working. I am passing in two parameters $arr and $value. Not sure why this is happening. Any help would be greatly appreciated. This is what I have so far:
<?php
$arr = array(
'a' => "one",
'b' => "two",
'c' => "three",
'd' => "two",
'e' => "four",
'f' => "five",
'g' => "three",
'h' => "two"
);
function removeAllValuesMatching($arr, $value){
foreach ($arr as $key => $value){
if ($arr[$key] == $value){
unset($arr[$key]);
}
}
return $arr = array_values($arr);
}
print_r(removeAllValuesMatching($arr, "two"));
?>
You're overwriting $value here:
foreach ($arr as $key => $value){
Simply rename it:
foreach ($arr as $key => $val) {
if ($val == $value) {
However, a better way to delete elements from an array is this:
function removeAllValuesMatching(array $arr, $value) {
$keys = array_keys($arr, $value);
foreach ($keys as $key) {
unset($arr[$key]);
}
return $arr;
}
This is my full version, with no variables collision and indenting : that's not an option, you should always indent correctly
<?php
$arr = array(
'a' => "one",
'b' => "two",
'c' => "three",
'd' => "two",
'e' => "four",
'f' => "five",
'g' => "three",
'h' => "two"
);
function removeAllValuesMatching($arr, $arg){
foreach ($arr as $key => $value){
if ($arr[$key] == $arg){
unset($arr[$key]);
}
}
return $arr = array_values($arr);
}
print_r(removeAllValuesMatching($arr, "two"));
?>
Not a fix for your method, but array_diff will acheive the same result, while also allowing you to remove multiple values.
$arr = [
'a' => "one",
'b' => "two",
'c' => "two",
'd' => "three",
];
$filtered = array_diff($arr, ['one', 'two']);
print_r($filtered); // Array([d] => three)
Related
I have a an array looking like this:
$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
I would like to sum values foreach "unique" key when only the first character is considered. The result should then be:
$newarray = array("a" => 3, "b" => 5);
I have tried using a foreach() loop within another foreach() loop like this:
foreach ($xml->children() as $output) {
foreach ($array as $key => $value) {
if (substr($key,0,1) == $output->KEY) {
$sum += $value; echo $sum;
}
}
}
It didn't work as the results apparently added the prior calculations.
Simple solution:
$final_array=[];
foreach($array as $key=>$value){
$final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
}
print_r($final_array);
Output:- https://3v4l.org/tZ4Ei
You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.
<?php
$sum = [];
foreach ($array as $key => $value) {
$letter = substr($key,0,1);
if (!isset($sum[$letter])){$sum[$letter] = 0;}
$sum[$letter] += $value;
}
var_dump($sum);
A simple isset should do it:
$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
$result = array();
foreach ($array as $oldkey => $val) {
$newkey = substr($oldkey, 0, 1);
if (isset($result[$newkey]) === false)
$result[$newkey] = $val;
else
$result[$newkey] += $val;
}
var_dump($result);
Try this way
$array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
$result = array();
foreach($array as $key => $value){
if(isset($result[$key[0]])){
$result[$key[0]] = $result[$key[0]]+$value;
} else {
$result[$key[0]] = $value;
}
}
print_r($result);
Quick and Easy, you can have any number of numbers in the array after the characters.
<?php
$array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
$newArray = [];
foreach ($array as $key => $value) {
$key = preg_replace("/[0-9]*$/", "", $key);
$newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
}
print_r($newArray);
I have two arrays.
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
I want to merge these two arrays and get following result.
$c = array('a' => 5, 'b' => 12, 'c' => 18);
What is the easiest way to archive this?
Thanks!
As mentioned in the comments, looping through the array will do the trick.
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
$c = array();
foreach($a as $index => $item) {
if(isset($b[$index])) {
$new_value = $a[$index] + $b[$index];
$c[$index] = $new_value;
}
}
$c = array();
foreach ($a as $k => $v) {
if (isset($b[$k])) {
$c[$k] = $b[$k] + $v;
}
}
You need to check whether keys exist in both arrays.
You can simply use foreach as
foreach($b as $key => $value){
if(in_array($key,array_keys($a)))
$result[$key] = $a[$key]+$value;
}
You can easily do this by foreach loop, please see the example below
$c = array();
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
foreach ($a as $key => $value) {
$tmp_value = $a[$key] + $b[$key];
$c[$key] = $tmp_value;
}
print_r($c);
Let's say I have an array like this:
$array = [
['a' => 'v', 'b' => 's', 'c' => 's'],
['c' => 's', 'd' => 's', 'b' => 's'],
['b' => 's', 'e' => 's', 'g' => 's'],
];
I want to create a new array which contains how many unique keys are found anywhere in my array's associative rows.
Desired result:
[
'a' => 1,
'b' => 3,
'c' => 2,
'd' => 1,
'e' => 1,
'g' => 1
]
I tried with array_count_values(), but it is not right for my array structure.
Some correction and addition to your answer.
$newArray = Array();
foreach ($array as $values) {
foreach ($values as $key => $value) {
if (!isset($newArray[$key]))
$newArray[$key] = 0; // create new 0 element
$newArray[$key]++;
}
}
Other functional approach
$result = array_count_values( // 3. count values
call_user_func_array('array_merge', // 2. merge array of keys
array_map('array_keys', $array))); // 1. convert inner array to array with keys
var_dump($result);
Second one, just replace loops with array_map
$result = array();
array_map(function($inner_array)use(&$result)
{
array_map(function($key)use(&$result)
{
$value = &$result[$key]; // reference trick
$value++;
}, array_keys($inner_array));
}, $array);
var_dump($result);
Third one, with array_reduce
$result = array_count_values(
array_reduce($array, function($result, $inner_array)
{
return array_merge($result, array_keys($inner_array)); // merge arrays one by one
}, []));
var_dump($result);
Here are some alternative and modernized techniques not mentioned by #sectus.
Codes: (Demo)
Functional-style with spread-flattening:
var_export(
array_count_values(
array_merge(
...array_map(
'array_keys',
$array
)
)
)
);
Classic nested loops with null coalescing operator:
$counts = [];
foreach ($array as $row) {
foreach ($row as $k => $v) {
$counts[$k] = ($counts[$k] ?? 0) + 1;
}
}
var_export($counts);
Recursive iteration to access only leaf-nodes:
$counts = [];
array_walk_recursive($array, function($v, $k) use(&$counts) {
$counts[$k] = ($counts[$k] ?? 0) + 1;
});
var_export($counts);
I do that, it is working, but i want to know if exists another method:
$newArray = Array();
foreach ($array as $values) {
foreach ($values as $key => $value) {
$newArray[$key]++;
}
}
With a basic associative array like:
$ar = array("First" => 1, "Second" , "Third" =>"Three");
if you do:
foreach($ar as $key => $val) {
var_dump($key);
}
This will produce:
string 'First' (length=5)
int 0
string 'Third' (length=5)
How do you Achieve the same results in a Multidimensional Array?
Something like:
array( 0 => array(
"First" => 1, "Two", "Third" => "Three"
)
);
I tried:
foreach($ar as $k => $v){
var_dump($ar[0][$k]);
}
I got:
string 'Two' (length=3)
Instead of:
string 'First' (length=5)
int 0
string 'Third' (length=5)
Thanx
function get_key(&$arr){
foreach($arr as $key=>$value){
if(is_array($value)){
get_key($value);
}else{
var_dump($key);
}
}
}
$arr = array(
'key1'=>array('a'=>1,'b'=>2),
'key2'=>array('c'=>1,2),
);
get_key($arr);
output:
string(1) "a"
string(1) "b"
string(1) "c"
int(0)
If $ar is equal to this:
array( 0 => array(
"First" => 1, "Two", "Third" => "Three"
)
);
You could iterate over the inner array to get the same result:
foreach ($ar as $k => $v) {
foreach ($v as $k2 => $v2) {
var_dump($k2);
}
}
Output:
string(5) "First"
int(0)
string(5) "Third"
You can iterate through the values of the inner array like this:
foreach($ar[0] as $k => $v){
var_dump($v);
}
The problem with yours is that you are only looping over 1 element in the ar array, and then applying that number to the array inside of it.
If you also want to do the same thing on both levels, you need another foreach loop like so:
foreach($ar as $k => $v){
foreach($v as $k => $n){
var_dump($n);
}
}
$arr = array(
0 => array("First" => 1, "Two", "Third" => "Three")
);
foreach ($arr as $key => $value)
{
foreach ($value as $k => $v)
{
var_dump($k);
}
}
You can access multidimensional Array keys and indexes like so:
$ary = array('whatever' => array('First' => 1, 'Two', 'Third' => 'Three'),
array('something' => array('cool' => 'yes', 'awesome' => 'super', 'great' => 10)
);
foreach($ary as $k => $a){
// $k is each Array key within initial Array
foreach($a as $i => $v){
// $i is internal index
// $v is internal value
}
}
Note:
In an Array that contains Arrays the first Array is really the value under key 0, unless the Array is assigned to a key, so your key, 0, is not necessary.
Probably a simple one for you :
I have 2 arrays
$array1 = array(
'foo' => 5,
'bar' => 10,
'baz' => 6
);
$array2 = array(
'x' => 100,
'y' => 200,
'baz' => 30
);
I wish to get a third array by combining both the above, which should be :
$result_array = array(
'foo' => 5,
'bar' => 10,
'baz' => 36,
'x' => 100,
'y' => 200,
);
Is there any built in 'array - way' to do this, or will I have to write my own function ?
Thanks
$resultArray = $array1;
foreach($array2 as $key => $value) {
if (isset($resultArray[$key])) {
$resultArray[$key] += $value;
} else {
$resultArray[$key] = $value;
}
}
There's no built-in function for this, you'll have to write your own.
you need
$newArray = $array1;
foreach($array2 as $key => $value) {
if(array_key_exists($key, $newArray)){
$newArray[$key] += $value;
}else{
$newArray[$key] = $value;
}
}