This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 6 years ago.
I have an array with values between 1-100. However, in case of an error, is there a way to make one final check just to be sure I skip/ignore values greater than 100 and the output is between 1-100?
This is where array_filter() comes in handy.
$lower_limit = 1;
$upper_limit = 100;
$array = array_filter(
$array,
function ($value) use ($lower_limit, $upper_limit) {
return ($value >= $lower_limit && $value <= $upper_limit);
}
);
Using array_filter is a way to it.
It will iterate through your array and filters it using the supplied function. In the end you'll get an array with only elements between 1 and 100.
$arr = array(
1, 2, 99, 201,
);
$goodArr = array_filter($arr, function($value){
return ($value >= 1 && $value <= 100);
});
Related
This question already has answers here:
Split associative array by key
(6 answers)
Get the first N elements of an array?
(5 answers)
php - get numeric index of associative array
(7 answers)
Closed 2 years ago.
There is an array in php
$sampleArray = array('first' => 'first', 'second' => 'second', 'third' => 'third');
I need to splitting the array based on value $check, if the $check is 'second', then the array need to be split like this
$requiredArray = array('third'=>'third')
$nonReqArray = array('first'=>'first','second'=>'second')
if the $check is 'third' then the $requiredArray will be empty. Please suggest the solution to this?
Tried with this
$afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check) {
if($key > $check){
$requiredArray[$key] = $key;
}else{
$nonReqArray[$key] = $key;
}
return true;
},
ARRAY_FILTER_USE_KEY);
Usually solved with for loops. But we can solve by array_filter array function. The main issue is indexing is not numerical, so comparing is not easy.
$cmp = false;
$afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check, &$cmp) {
if($cmp){
$requiredArray[$key] = $key;
}else{
$nonReqArray[$key] = $key;
}
if($key == $check){
$cmp =true;
}
return true;
},
ARRAY_FILTER_USE_KEY);
This worked for me.
This question already has answers here:
How to search Array for multiple values in PHP?
(6 answers)
Closed 2 years ago.
there is an array like $arr = array(1,2,3,3,3,4,5) . What if we want to get all indexes that have values 3?
i used array_search(3, $arr) but it just give back an integer and just the first index that has value '3'
how can we get an array like $indexes = array(2,3,4) that shows all indexes that have value 3?
your help will be highly appreciated
You can use array_keys with search value PHP Doc
Demo
array_keys($arr,3)
array_keys() returns the keys, numeric and string, from the array.
If a search_value is specified, then only the keys for that value are
returned. Otherwise, all the keys from the array are returned.
you can use array_keys:
foreach (array_keys($arr) as $key) if ($arr[$key] == 3) $result[] = $key;
With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped.
$a = [1,2,3,4,3,3,5,6];
$threes = array_filter($a, function($v, $k) {
return $v === 3 ? $k : false; },
ARRAY_FILTER_USE_BOTH
);
$threes Is an array containing all keys having the value 3.
array(3) { 2, 4, 5 }
This question already has answers here:
How to filter an array by a condition
(9 answers)
get specific column with specific condition from multidimensional array using array function only in php
(4 answers)
Closed 3 years ago.
I have a multi-column PHP array as
Array (
Array ('col1', 'col2', 'col3'),
);
How can I get an array of col2 if col1 is greater than a specific value?
I can do it by a foreach loop, but I think it should be possible with a native function like array_filter.
Simply put, you're better with a foreach loop, as you're not going to have to make multiple iterations of the array. You want to both filter and modify the array, which requires using both array_filter() and array_map() in order to get what you want:
<?php
$arr = [
[5, 'col2-1', 'col3'],
[10, 'col2-2', 'col3']
];
$res = array_filter($arr, function($item) {
return $item[0] > 7;
});
$res = array_map(function($item) {
return $item[1];
}, $res);
var_dump($res);
Test here: https://3v4l.org/HRTOJ
This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 9 years ago.
i have this below array:
PHP
$arr=array('A','A','B','C');
i want to check value and if values are duplicate must be alert error
PHP
$chk=array_count_values($array);
if ( $chk[0] < 1 || $chk[2] < 1 || $chk[3] < 1 || $chk[4] < 1 )
echo 'array must be uniq';
Using array_unique(), this can be easily refactored into a new function:
function array_is_unique($array) {
return array_unique($array) == $array;
}
Example:
$array = array("a", "a", "b", "c");
echo array_is_unique($array) ? "unique" : "non-unique"; //"non-unique"
Try this :
$arr = array('A','A','B','C');
if(count($arr) != count(array_unique($arr))){
echo "array must be uniq";
}
Just try with:
if ( count($arr) != count(array_unique($arr)) ) {
echo 'array must be uniq';
}
You could walk thhrough it with a foreach loop and then use the strpos function to see if a string contains duplicates
From Php documentation
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
This question already has answers here:
Sum values of multidimensional array by key without loop
(5 answers)
Closed 10 months ago.
How can I calculate the value of one string containing few values?
For example,
$toPluck = 'price';
$arr = $gamesWorth;
$plucked = array_map(function($item) use($toPluck) {
echo $item[$toPluck];
}, $arr);
The webpage displays 2, 20, and 50.
I want to calculate them both and echo to the page 72.
I tried to find a solution on the web and on that website, but I can't find it..
Seems like a job for array_reduce
$toPluck = 'price';
$arr = array(
array('price' => 2),
array('price' => 20),
array('price' => 50),
);
echo array_reduce($arr, function($sum, $item) use($toPluck) {
return $sum + $item[$toPluck];
}, 0);
There are a few ways to handle it, but a simple modification to your existing code would be to return values from your array_map() and sum the resultant array with array_sum().
$toPluck = 'price';
$arr = $gamesWorth;
$plucked = array_map(function($item) use($toPluck) {
// Uncomment this if you want to print individual values
// Otherwise the array_map() produces no output to the screen
// echo $item[$toPluck];
// And return the value you need
return $item[$toPluck];
}, $arr);
// $plucked is now an array
echo array_sum($plucked);