Remove Values from PHP Array if Present - php

I have the following PHP array:
Array
(
[0] => 750
[1] => 563
[2] => 605
[3] => 598
[4] => 593
)
I need to perform the following action on the array using PHP:
Search the array for a value (the value will be in a
variable; let's call it $number). If the value
is present in the array, remove it.
If someone could walk me through how to do that, it would be much appreciated.
Note: If it makes it any easier, I can form the array so the keys are the same as the values.

$array = array_unique($array) // removes dupicate values
while(false !== ($num = array_search($num, $array))){
unset($array[$num]);
}
$max = max($array);
will search for all keys with value $num and unset them

lets say your $array
$array = array_unique($array) // removes dupicate values
$array = arsort($array)
$variable = $array[0] // the maximum value in the array, and place it in a variable.
$key = array_search($array, $number);
if($key){
unset($array[$key]) // Search array for a value, value is present in array, remove it.
}

array_search() and unset() seems a good method for your sample data in your question. I'll just show a different way for comparison's sake (or in case your use case is slightly different from what you have posted here).
Methods: (Demo)
$array=[750,563,605,598,593];
// if removing just one number apply the number as an array element
$number=605;
var_export(array_diff($array,[$number]));
// if you are performing this task with more than one $number, make $numbers=array() and do the same...
$numbers=[605,563]; // order doesn't matter
var_export(array_diff($array,$numbers));
// if you need to re-index the output array, use array_values()...
$numbers=[605,563]; // order doesn't matter
var_export(array_values(array_diff($array,$numbers)));
Output:
array (
0 => 750,
1 => 563,
3 => 598,
4 => 593,
)
array (
0 => 750,
3 => 598,
4 => 593,
)
array (
0 => 750,
1 => 598,
2 => 593,
)

Related

PHP - unset array where Key is X and Value is Y

I have this type of array,
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
[1] => Array --> I want to remove this value using its index, which is "1"
(
[id] => 2
[fams] => 5
)
)
I want to remove that array [1] entirely, using its index, so the condition is - where the ID is match, for example - [id] => 2
Is that possible, to remove a particular value with that specific condition?
and without looping (or any similar method that need to loop the array)
thanks in advance!
FYI - I did try to search around, but, to be honest, I'm not sure what "keyword" do I need to use.
I did try before, but I found, array_search, array_keys - and it seems those 2 are not.
I'm okay, if we need several steps, as long as it did not use "loop" method.
---update
I forgot to mention, that I'm using old PHP 5.3.
array_filter should work fine with PHP 5.3.
The downside of this approach is that array_filter will (internally) iterate over all your array's entries, even after finding the right one (it's not a "short-circuit" approach). But at least, it's quick to write and shouldn't make much of a difference unless you're dealing with very big arrays.
Note: you should definitely upgrade your PHP version anyway!
$array = array (
0 =>
array (
'id' => 0,
'fams' => 5
),
1 =>
array (
'id' => 2,
'fams' => 5
)
);
$indexToRemove = 2;
$resultArray = array_filter($array, function ($entry) use ($indexToRemove) {
return $entry['id'] !== $indexToRemove;
});
Demo: https://3v4l.org/6DXjl
You can use array_search to find the key of a sub-array that has a matching id value (extracted using array_column), and if found, unset that element:
if (($k = array_search(2, array_column($array, 'id'))) !== false) {
unset($array[$k]);
}
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
)
Demo on 3v4l.org
It should be noted that although there is no explicit loop in this code, array_search and array_column both loop through the array internally.
You can use array_column to make id as index of the sub-array then use unset
$a = array_column($a, null, 'id');//new array id as index
$index = 2;// id to remove
if($a[$index]) unset($a[$index]);
print_r($a);
Working example :- https://3v4l.org/ofMr7

Get values of array using as key values of another array

I have an array with some values (numeric values):
$arr1 = [1, 3, 8, 12, 23]
and I have another associative array that a key (which matches to a value of $arr1) correspond to a value. This array may contain also keys that don't match with $arr1.
$arr2 = [1 => "foo", 2 => "foo98", 3 => "foo20", 8 => "foo02", 12 => "foo39", 15 => "foo44", 23 => "foo91", 34 => "foo77"]
I want as return the values of $arr2 specifying as key the values of $arr1:
["foo", "foo20", "foo02", "foo39", "foo91"]
If possible, all this, without loops, using just PHP array native functions (so in an elegant way), or at least with the minimum number of loops possible.
Minimal loop is simple - 1. as:
foreach($arr1 as $k) {
$res[] = $arr2[$k];
}
You can do that with array_walk but I think this simple way is more readable.
If you insist you can do with array_filter + array_values + in_array as:
$res = array_values(array_filter($arr2,
function ($key) use ($arr1) { return in_array($key, $arr1);},
ARRAY_FILTER_USE_KEY
));
You can see this for more about filtering keys
To do it purely with array functions, you could do it as...
print_r(array_intersect_key($arr2, array_flip($arr1) ));
So array_flip() turns the items you want form the array into the keys for $arr1 and then uses array_intersect_key() to match the keys with the main array and this newly created array.
Gives...
Array
(
[1] => foo
[3] => foo20
[8] => foo02
[12] => foo39
[23] => foo91
)
If you don't want the keys - add array_values() around the rest of the calls...
print_r(array_values(array_intersect_key($arr2, array_flip($arr1) )));
to get
Array
(
[0] => foo
[1] => foo20
[2] => foo02
[3] => foo39
[4] => foo91
)
Although as pointed out - sometimes a simple foreach() is just as good and sometimes better.

check if value explode in array is duplicated with another explode value

hello try to find the duplicated value in array i have array like that
$array = array('1%2','3%4','1%2',1%3);
so i want to find duplicated 2 after % so i used explode inside foreach
foreach($array as $value){
$s = explode('%',$value);
if($s[1] == $s[1]){
echo 'there are duplicated 2';
}
}
so i want $s[1] check if value after % in array is duplicated
is there anyway to do that
You will need to collect the right side values as you loop through them and check for duplicates. I am accessing the strings' right side values via their "offset" [2]. When found, you can exit the loop with a break.
Code: (Demo)
$array=['1%2','3%4','1%2','1%3'];
$kept=[];
foreach($array as $i=>$v){
if(in_array($v[2],$kept)){
echo "Element (index $i) containing $v has duplicate right side value.";
break;
}
$kept[]=$v[2];
}
Output:
Element (index 2) containing 1%2 has duplicate right side value.
If you want to search for all element that end with %2, you can use preg_grep().
Code:
$search=2;
$array=['1%2','1%3','1%4','3%2','5%2'];
var_export(preg_grep("/%{$search}$/",$array));
Output:
array (
0 => '1%2',
3 => '3%2',
4 => '5%2',
)
Or without regex, it will require more function calls:
$search=2;
$array=['21%2','1%3','2%22','1%4','3%21','5%2'];
var_export(array_filter($array,function($v)use($search){return strpos($v,"%$search")+2===strlen($v);}));
Output:
array (
0 => '21%2',
5 => '5%2',
)
...[deep breath] Here is attempted answer #4...
Code:
$array=['1%2','1%3','1%4','3%2','5%2'];
foreach($array as $v){
$grouped[explode('%',$v)[1]][]=$v; // use right side number as key
}
var_export($grouped);
Output:
array (
2 =>
array (
0 => '1%2',
1 => '3%2',
2 => '5%2',
),
3 =>
array (
0 => '1%3',
),
4 =>
array (
0 => '1%4',
),
)
If you want to count the right side values in the array:
$array=['1%2','1%3','1%4','3%2','5%2'];
$array=preg_replace('/\d+%/','',$array); // strip the left-size and % from elements
var_export(array_count_values($array)); // count occurrences
Output:
// [right side values] => [counts]
array (
2 => 3,
3 => 1,
4 => 1,
)

Sum of array values based on similar values from another array

This might be a little confusing, but I am going to explain it as best as I can. Please bear with me.
I have the following arrays:
Array
(
[question1] => 69
[question2] => 36
[question3] => 57
[question4] => 69
[question5] => 58
[question6] => 40
[question7] => 58
)
Array
(
[question1] => 8
[question2] => 6
[question3] => 5
[question4] => 6
[question5] => 7
[question6] => 8
[question7] => 5
)
As you can see the two arrays have identical keys, but different values for each key.
I need to find the keys in the second array that have the same values, so [question1] and [question6] both have a value of 8. And then in the first array I need to add together the values of [question1] and [question6] because they have a like value in the second array. I need to add the first array values together based on matching values in the second array (if that makes any sense)
Ideally, the output would be another array that would look something like this:
Array
(
[5] => 115
[8] => 109
[6] => 105
[7] => 58
)
Where the value of the second array becomes the key and the sum of the added values from the first array is the value.
Now I won't be picky here, so if we can't get it into that exact format then that is okay. I just need to be able to add together the values in the first array based on the similar values in the second array.
I hope this makes sense. If it doesn't please comment and I will do my best to explain further.
The simplest solution is to iterate over the second array. Lookup the key into the first array and if it exists then add the corresponding value from the first array into the result array, indexed by the value from the second array.
Something like this:
$array1 = array(
'question1' => 69,
'question2' => 36,
'question3' => 57,
'question4' => 69,
'question5' => 58,
'question6' => 40,
'question7' => 58,
);
$array2 = array(
'question1' => 8,
'question2' => 6,
'question3' => 5,
'question4' => 6,
'question5' => 7,
'question6' => 8,
'question7' => 5,
);
// Compose the desired result here
$result = array();
// Iterate over the second array; its values become keys in the result array
foreach ($array2 as $key => $val) {
// If this is the first time when this value is reached then a corresponding
// value does not yet exists in the result array; add it
if (! isset($result[$val])) {
$result[$val] = 0;
}
// Lookup the key into the first array
if (isset($array1[$key])) {
// If it exists then add its value to the results
$result[$val] += $array1[$key];
}
}
// That's all
print_r($result);

PHP: Ignore key and extract value of an array

I have a function that returns an array where the value is an array like below: I want to ignore the key and extract the value directly. How can I do this without a for loop? The returned function only has one key but the key (2 in this case) can be a variable
Array ( [2] => Array ( [productID] => 1 [offerid]=>1)
Expected result:
Array ( [productID] => 1 [offerid]=>1)
There're at least 3 ways of doing this:
Use current function, but be sure that array pointer is in the beginning of your array:
$array = Array (2 => Array ( 'productID' => 1, 'offerid' => 1));
$cur = current($array);
var_dump($cur, $cur['offerid']);
Next is array_values function, which will give you array of values with numeric keys, starting with 0
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$av = array_values($array);
var_dump($av[0], $av[0]['offerid']);
And third option is use array_shift, this function will return first element of array, but be careful as it reduces the original array:
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$first = array_shift($array);
var_dump($first, $first['offerid']);
If you want to get the current value of an array, you can use current() assuming the array pointer is in the correct position. If there is only one value, then this should work fine.
http://php.net/manual/en/function.current.php
I think Devon's answer will work for you , but if not your can try
$arr = array_column($arr, $arr[2]);
if you need always the second index of your master array, if you need all index use
array_map(),
something like array_map('array_map', $arr); should work.

Categories