Count negative values in a PHP array - php

I have an array which looks something like this:
array(-2, -1, 0, 1, 2, 3, 4)
I would like to count the number of negative numbers only. I can't spot where it says how to do this in the manual, is there no function to do this? Do I have to create a loop to go through the array manually?

Do I have to create a loop to go through the array manually?
Yes, you have to do it manually by easily doing:
function count_negatives(array $array) {
$i = 0;
foreach ($array as $x)
if ($x < 0) $i++;
return $i;
}
At the end of the script $i will contain the number of negative numbers.

I should use this:
$array = array(-2, -1, 0, 1, 2, 3, 4);
function negative($int) {
return ($int < 0);
}
var_dump(count(array_filter($array, "negative")));

You can use array_filter
function neg($var){
if($var < 0){
return $var;
}
}
$array1 = array(-2, -1, 0, 1, 2, 3, 4);
print count(array_filter($array1, "neg"));

Use array_filter http://www.php.net/manual/en/function.array-filter.php
function isnegative($value){
return is_numeric($value) && $value < 0;
}
$arr = array_filter(array(-1,2,3,-4), 'isnegative');
echo length($arr);
Have fun.

Try this:
$aValues = array(1, 2, 3, -1, -2, -3, 0);
echo sizeof(array_filter($aValues, create_function('$v', 'return $v < 0;')));

Related

Select only elements you want in string/array

I have an array like this $arr = array(2, -3, 6, 1);
And I only want to select the positive numbers to be able to sum the others between them.
So I wrote this code, but I'm a bit lost on how to select the elements I only want to do something with them, like summing them.
$sum = implode(",", $arr);
for($i = 0; $i <= strlen($sum); $i++) {
if($i <= 0) {
} else {
return explode(",", array_sum($i));
}
}
}
Use array_fliter to filter the value, and array_sum to sum the array.
array_sum(array_filter($array, function($v){return $v>0;});
Use array_filter with callback function like below :
<?php
$arr = array(2, -3, 6, 1);
function positive($a){
if($a > 0){
return $a;
}
}
$newArr = array_sum(array_filter($arr, "positive"));
print_r($newArr);
?>
Using array_reduce:
$arr = array(2, -3, 6, 1);
$result = array_reduce($arr, function($c, $i) { return $i > 0 ? $c + $i : $c; });
echo $result;

finding the index of last occurrence of an element in an array using binary search PHP

The array given has duplicate elements, So basically, I want to find the index of the last occurrence of the element I've searched.
$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
$x = 4; // number to search
$low = 0;
$high = count($arr)-1;
// I want this function to return 6 which is the index of the last occurrence of 4, but instead I'm getting -1 .
function binary_search_last_occ($arr, $x, $low, $high)
{
while ($low <=$high)
{
$mid = floor(($low+$high)/2);
$result = -1;
if ($arr[$mid] == $x)
{
// we want to find last occurrence, so go for
// elements on the right side of the mid
$result = $mid;
$low = $mid+1;
}
else if($arr[$mid] > $x)
{
$high = $mid-1;
}
else
$low = $mid+1;
}
return $result;
}
echo binary_search_last_occ($arr, $x, $low, $high); // outputs -1 ?
I'm not sure, why I'm getting -1. Any suggestions?
I didn't seen your loop but I think this'll really simple to use to gain such functionality
$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
$result = [];
foreach($arr as $key => $val){
$result[$val][] = $key;
}
echo end($result[4]);//6
Or you can simply use the asort function along with array_search like as
$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
asort($arr);
echo array_search(4,$arr);//6
First of all for binary search your array must be sorted, if your array is not sorted you can use simple method like
function binary_search_last_occ($arr, $x, $low, $high)
{
$last_occ = -1;
while ($low <=$high)
{
if($arr[$low] == $x)
$last_occ = $low;
$low++;
}
return $last_occ ;
}
And also define $result above while() to avoid overriding every time with -1. Hence you get the result as -1.
$result = -1;
while ($low <=$high)
{
$mid = floor(($low+$high)/2);
if ($arr[$mid] == $x)
{
// we want to find last occurrence, so go for
// elements on the right side of the mid
$result = $mid;
$low = $mid+1;
}
else if($arr[$mid] > $x)
{
$high = $mid-1;
}
else
$low = $mid+1;
}
return $result;

Remove duplicates of array

I was just going through these questions for PHP and got stuck at one of them. The question is:
You have a PHP 1 dimensional array. Please write a PHP function that
takes 1 array as its parameter and returns an array. The function must
delete values in the input array that shows up 3 times or more?
For example, if you give the function
array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9)the function will returnarray(1, 3, 5, 2, 3, 1, 9)
I was able to check if they are repeating themselves but I apply it to the array I am getting as input.
function removeDuplicate($array){
$result = array_count_values( $array );
$values = implode(" ", array_values($result));
echo $values . "<br>";
}
$qArray = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
removeDuplicate($qArray);
One more thing, we cannot use array_unique because it includes the value which is repeated and in question we totally remove them from the current array.
Assuming the value may not appear 3+ times anywhere in the array:
$array = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
// create array indexed by the numbers to remove
$remove = array_filter(array_count_values($array), function($value) {
return $value >= 3;
});
// filter the original array
$results = array_values(array_filter($array, function($value) use ($remove) {
return !array_key_exists($value, $remove);
}));
If values may not appear 3+ times consecutively:
$results = [];
for ($i = 0, $n = count($array); $i != $n;) {
$p = $i++;
// find repeated characters
while ($i != $n && $array[$p] === $array[$i]) {
++$i;
}
if ($i - $p < 3) {
// add to results
$results += array_fill(count($results), $i - $p, $array[$p]);
}
}
This should work :
function removeDuplicate($array) {
foreach ($array as $key => $val) {
$new[$val] ++;
if ($new[$val] >= 3)
unset($array[$key]);
}
return $array;
}
run this function i hope this help..
function removeDuplicate($array){
$result = array_count_values( $array );
$dub = array();
$answer = array();
foreach($result as $key => $val) {
if($val >= 3) {
$dub[] = $key;
}
}
foreach($array as $val) {
if(!in_array($val, $dub)) {
$answer[] = $val;
}
}
return $answer;
}
You can use this function with any number of occurrences you want - by default 3
function removeDuplicate($arr, $x = 3){
$new = $rem = array();
foreach($arr as $val) {
$new[$val]++;
if($new[$val]>=$x){
$rem[$val]=$new[$val];
}
}
$new = array_keys(array_diff_key($new, $rem));
return $new;
}
I think it is getting correct output. just try once.
$array=array(1,2,3,7,4,4,3,5,5,6,7);
$count=count($array);
$k=array();
for($i=0;$i<=$count;$i++)
{
if(!in_array($array[$i],$k))
{
$k[]=$array[$i];
}
}
array_pop($k);
print_r($k);
in this first $k is an empty array,after that we are inserting values into $k.
You should use array_unique funciton.
<?php
$q = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
print_r(array_unique($q));
?>
Try it and let me know if it worked.

PHP create array where key and value is same

I am using the range() function to create an array. However, I want the keys to be the same as the value. This is ok when i do range(0, 10) as the index starts from 0, however if i do range(1, 11), the index will still start from 0, so it ends up 0=>1 when i want it to be 1=>1
How can I use range() to create an array where the key is the same as the value?
How about array_combine?
$b = array_combine(range(1,10), range(1,10));
Or you did it this way:
$b = array_slice(range(0,10), 1, NULL, TRUE);
Find the output here: http://codepad.org/gx9QH7ES
There is no out of the box solution for this. You will have to create the array yourself, like so:
$temp = array();
foreach(range(1, 11) as $n) {
$temp[$n] = $n;
}
But, more importantly, why do you need this? You can just use the value itself?
<?php
function createArray($start, $end){
$arr = array();
foreach(range($start, $end) as $number){
$arr[$number] = $number;
}
return $arr;
}
print_r(createArray(1, 10));
?>
See output here: http://codepad.org/Z4lFSyMy
<?php
$array = array();
foreach (range(1,11) as $r)
$array[$r] = $r;
print_r($array);
?>
Create a function to make this:
if (! function_exists('sequence_equal'))
{
function sequence_equal($low, $hight, $step = 1)
{
return array_combine($range = range($low, $hight, $step), $range);
}
}
Using:
print_r(sequence_equal(1, 10, 2));
Output:
array (
1 => 1,
3 => 3,
5 => 5,
7 => 7,
9 => 9,
)
In PHP 5.5 >= you can use Generator to make this:
function sequence_equal($low, $hight, $step = 1)
{
for ($i = $low; $i < $hight; $i += $step) {
yield $i => $i;
}
}

PHP: Minimum value in 2D array

I have a 2D array in the format:
[
[1, 23, 20],
[2, 45, 30],
[4, 63, 40],
...
]
I am trying to search the array and return elements [0] and [1] from the row where element [1] is lowest. I have the following code to return the lowest value in [1] but I'm not sure how to get element [0] as well.
$min = PHP_INT_MAX;
foreach ($test as $i) {
$min = min($min, $i[1]);
}
In the above example I would return [1, 23]
Thanks,
You should use usort for this:
usort($test, function($a, $b) {
return $a[1] - $b[1];
});
$min = $test[0];
Note that this uses anonymous functions, which were introduced in PHP 5.3. In previous versions, you need to use named functions and pass the name as a string to usort.
You could use array_reduce:
$array = array(
array(1, 23, 20),
array(2, 45, 63),
array(4, 63, 40),
);
$callback = function ($a1, $a2) {
if ($a1[1] >= $a2[1]) {
return $a2;
} else {
return $a1;
}
}
$min = array_reduce($array, $callback, array(0, PHP_INT_MAX, 0));
var_dump($min); // array(1, 23, 20);
Now, this will likely have issues if you have multiple elements with identical [1] elements... But it transparently handles the case where the array is empty. And in general, all you need to do is do your comparison in the callback function for all "filtering" type problems where you can abstract the filtering to a comparison of 2 elements. So you do string comparison, etc to determine which of the 2 is better...
And it should be more efficient than a sort, since it only requires a single pass over the array (It's O(n) whereas sorting is O(n log n) and at worst O(n^2))...
This will do the job.
$min0 = PHP_INT_MAX;
$min1 = PHP_INT_MAX;
foreach ($test as $i) {
if($i[1] < $min1)
{
$min0 = $i[0];
$min1 = $i[1];
}
}
This will result in $min0 == 1 and $min1 == 23
You'll need to introduce some basic logic:
$result = array(0, PHP_INT_MAX);
foreach($test as $i)
if($i < $result[1])
$result = array($i[0], $i[1]);
You can use a simple min (O(n)) loop like you did, and array_slice to assign the first two indexes when a lowest is found :
$min = PHP_INT_MAX;
$arrMin = array();
foreach ($test as $i) {
if ($i[1] < $min) {
$min = $i[1];
$arrMin = array_slice($i, 0, 2);
}
}
you should just grab the array key of the smallest number:
$min = PHP_INT_MAX;
$minkey = 0;
foreach ($test as $key => $i) {
if($min > $i[1]) {
$min = $i[1];
$minkey = $key;
}
}
then, you can just access the whole thing with $test[$minkey]

Categories