I have the following array:
$array = [2,2,5,2,2];
I would like to get the number which is different from the others, for example all the numbers are 2 except the number 5. So Is there anyway to get the different number using any array method or better solution? My solution is:
$array = [2,2,5,2,2];
$array1 = [4,4,4,6,4,4,4];
$element = -1;
$n = -1;
$count = 0;
for($i=0; $i<count($array1); $i++) {
if($element !== $array1[$i] && $element !== -1 & $count==0) {
$n = $array1[$i];
$count++;
}
$element = $array1[$i];
}
dd($n);
You can use array_count_values for group and count same value like:
$array = [2,2,5,2,2];
$countarray = array_count_values($array);
arsort($countarray);
$result = array_keys($countarray)[1]; // 5
Since you only have two numbers, you will always have the number with the least equal values ββin second position
Reference:
array_count_values
array_keys
A small clarification, for safety it is better to use arsort to set the value in second position because if the smallest number is in first position it will appear as the first value in the array
Sorting Arrays
You can user array_count_values which returns array with item frequency.
Then use array_filter to filter out data as follow:
$arrayData = [2,2,2,5];
$filterData = array_filter(array_count_values($arrayData), function ($value) {
return $value == 1;
});
print_r($filterData);
Inside array_filter(), return $value == 1 means only get the data with 1 frequency and thus filter out the other data.
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
print $number . ' | ' . ($count > 1 ? 'Duplicate value ' : 'Unique value ') . "\n";
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
UniqueAndDuplicat($array1);
//output: 2 | duplicate value 5 | Unique value
UniqueAndDuplicat($array2);
//output: 4 | duplicate value 5 | Unique value
?>
Use this function to reuse this you just call this function and pass an Array to this function it will give both unique and duplicate numbers.
If you want to return only Unique number then use the below code:
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
if($count == 1){
return $number;
}
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
echo UniqueAndDuplicat($array1); // 5
echo "<br>";
echo UniqueAndDuplicat($array2); // 6
?>
Related
I am a rookie beginner with PHP, i was wondering how i could add up the total number from 1 array + the total number of another array together. I managed to make this code with help from stackoverflow answers on google. I don't know why but it's no where explained or i am looking over it. Been looking for almost an hour to make this work. Here is the code:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
$odds = array();
$even = array();
foreach($array as $val) {
if($val % 2 == 0) {
$even[] = $val;
} else {
$odds[] = $val;
}
}
$array = array();
foreach($even as $key => $val) {
$array[] = $val;
if(isset($odds[$key])) {
$array[] = $odds[$key];
}
}
echo '<b>Oneven</b> ';
print_r($odds);
echo '<br><br><br>';
echo "Bovenstaande <b>oneven</b> getallen bijelkaar opgeteld = " . array_sum($odds) . "\n";
echo '<br><br><br><hr style="margin-top:2%;margin-bottom:4%;">';
/* Array nummer 2 */
$array = array(20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40);
$odds = array();
$even = array();
foreach($array as $val) {
if($val % 2 == 0) {
$even[] = $val;
} else {
$odds[] = $val;
}
}
$array = array();
foreach($even as $key => $val) {
$array[] = $val;
if(isset($odds[$key])) {
$array[] = $odds[$key];
}
}
echo '<b>Even</b> ';
print_r($even);
echo '<br><br><br>';
echo "Bovenstaande <b>even</b> getallen bijelkaar opgeteld = " . array_sum($even) . "\n";
?>
So i don't know how to do it in another way but i have array 1 code at first and then code 2 begins with another array.
The thing is that i want to make a program that includes the odd numbers from 1 to 19 and the even numbers from 20 to 40 and then count the total of those 2 array's. Is there a way to do this in 1 code and count up the total of those 2 array's together. I already have that part of code that it counts the array, in code 1 that is 100 and in code 2 it is 330.
330+100=430 that's the output that i want. Why is that so hard? haha...
I appreciate the help and time effort.
First off, there's a lot of complexity involved in creating the initial array and then extracting only the odd numbers. This complexity can be eliminating by using the range and array_filter functions like so:
$odds = array_filter(range(1, 19), function($elem) {
return $elem & 1;
});
$even = array_filter(range(20, 40), function($elem) {
return $elem % 2 == 0;
});
to calculate sum of the sum of odds plus the sum of even, you can simply merge them together and use array_sum in the same you are doing for the individual arrays
$totalSum = array_sum(array_merge($odds, $even))
As #Darragh pointed out in the comments, you can simplify the array creation by specifying a step parameter for the range function.
$odds = range(1, 19, 2) // start at 1, go up to 19, by increments of 2
I am still beginner.
I want to subtract a value in an array, then I want to compare values. I have an array, the values are not known, depend on the result of a function.
Example :
$value = [5,8,13,15];
I want to subtract each value and save it in an array. Example :
8-5 = 3
13-8 = 5
15-13 = 2
then I want to compare each value (3, 5, 2), which one is bigger.
Please help me. Thank you before.
$value = [5,18,13,15];
sort($value); //to not get negative results
$loop = 0;
$results = array();
while ($loop < count($value))
{
if ($loop == 0)
{
$loop++;
}
else
{
$firstval = $value[$loop];
$secondval = $value[$loop-1];
$results[] = intval($firstval) - intval($secondval);
$loop++;
}
}
sort($results);
$thebiggestkey = $results[count($results)-1];
This should do it for you
A small example with Indexes and Array, if you here is wishes it you can use Foreach to subtract all that there is in the Array
( http://php.net/manual/en/control-structures.foreach.php )
$value = [5,8,3,13,15];
$rep = $value[0] - $value[1];
//5 - 8
echo $rep;
//return -3
I'm using the following code to retrieve the highest 3 numbers from an array.
$a = array(1,2,5,10,15,20,10,15);
arsort($a, SORT_NUMERIC);
$highest = array_slice($a, 0, 3);
This code correctly gives me the highest three numbers array(20,15,10); however, I'm interested in getting the highest 3 numbers including the ones that are identical. In this example, I'm expecting to get an array like array(10, 10, 15, 15, 20)
Might be simpler but my brain is tired. Use arsort() to get the highest first, count the values to get unique keys with their count and slice the first 3 (make sure to pass true to preserve keys):
arsort($a, SORT_NUMERIC);
$counts = array_slice(array_count_values($a), 0, 3, true);
Then loop those 3 and fill an array with the number value the number of times it was counted and merge with the previous result:
$highest = array();
foreach($counts as $value => $count) {
$highest = array_merge($highest, array_fill(0, $count, $value));
}
You can use a function like this:
$a = array(1,2,5,10,15,20,10,15); //-- Original Array
function get3highest($a){
$h = array(); //-- highest
if(count($a) >= 3){ //-- Checking length
$c = 0; //-- Counter
while ($c < 3 || in_array($a[count($a)-1],$h) ){ //-- 3 elements or repeated value
$max = array_pop($a);
if(!in_array($max,$h)){
++$c;
}
$h[] = $max;
}
sort($h); //-- sorting
}
return $h; //-- values
}
print_r(get3Highest($a));
Of course you can improve this function to accept a dinamic value of "highest" values.
The below function may be usefull
$a = array(1,2,5,10,15,20,10,15);
function getMaxValue($array,$n){
$max_array = array(); // array to store all the max values
for($i=0;$i<$n;$i++){ // loop to get number of highest values
$keys = array_keys($array,max($array)); // get keys
if(is_array($keys)){ // if keys is array
foreach($keys as $v){ // loop array
$max_array[]=$array[$v]; // set values to max_array
unset($array[$v]); // unset the keys to get next max value
}
}else{ // if not array
$max_array[]=$array[$keys]; // set values to max_array
unset($array[$keys]); // unset the keys to get next max value
}
}
return $max_array;
}
$g = getMaxValue($a,3);
Out Put:
Array
(
[0] => 20
[1] => 15
[2] => 15
[3] => 10
[4] => 10
)
You can modify it to add conditions.
I thought of a couple of other possibilities.
First one:
Find the lowest of the top three values
$min = array_slice(array_unique($a, SORT_NUMERIC), -3)[0];
Filter out any lower values
$top3 = array_filter($a, function($x) use ($min) { return $x >= $min; });
Sort the result
sort($top3);
Advantages: less code
Disadvantages: less inefficient (sorts, iterates the entire array, sorts the result)
Second one:
Sort the array in reverse order
rsort($a);
Iterate the array, appending items to your result array until you've appended three distinct items.
$n = 0;
$prev = null;
$top = [];
foreach ($a as $x) {
if ($x != $prev) $n++;
if ($n > 3) break;
$top[] = $x;
$prev = $x;
}
Advantages: more efficient (sorts only once, iterates only as much as necessary)
Disadvantages: more code
This gives the results in descending order. You can optionally use array_unshift($top, $x) instead of $top[] = $x; to get it in ascending order, but I think I've read that array_unshift is less efficient because it reindexes the array after each addition, so if optimization is important it would probably be better to just use $top[] = $x; and then iterate the result in reverse order.
I have an array of about 100 different random number like this:
$numbers=array(10,9,5,12, ..... .... ... ...);
now i want to make an array of random numbers from this array so that addition of selected numbers will be my given number. example: i may ask to get array of numbers such that, if i add all numbers it will be 100.
i am trying to do it in this way,
function rendom_num ($array,$addition)
{
//here is the code
}
print_r (rendome_num ($numbers,100));
i am not able to fiend the code for last 3 days!
Please use shuffle-
<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
php.net
can use shuffle as #chatfun said or can try array_rand if want only some random values from your array
$value= array("Rabin","Reid","Cris","KVJ","John");
$rand_keys=array_rand($value,2);
echo "First random element = ".$value[$rand_keys[0]];
echo "<br>Second random element = ".$value[$rand_keys[1]];
Something like this should work. The breakdown is commented so you know what it's all doing.
function Randomizer($number = 100)
{
// This just generates a 100 number array from 1 to 100
for($i=1; $i <= 100; $i++) {
$array[] = $i;
}
// Shuffles the above array (you may already have this array made so you would need to input into this function)
shuffle($array);
// Assign 0 as base sum
$sum = 0;
// Go through the array and add up values
foreach($array as $value) {
// If the sum is not the input value and is also less, continue
if($sum !== $number && $sum < $number) {
// Check that the sum and value are not greater than the input
if(($sum + $value) <= $number) {
// If not, then add
$sum += $value;
$new[] = $value;
}
}
// Return the array when value hit
else
return $new;
}
// If the loop goes through to the end without a successful addition
// Try it all again until it does.
if($sum !== $number)
return Randomizer($number);
}
// Initialize function
$test = Randomizer(100);
echo '<pre>';
// Total (for testing)
echo array_sum($test);
// Array of random values
print_r($test);
echo '</pre>';
i have an array with many values and i want to get one value is many show of all values. Like this.
my array
$allValues = array(0,1,1); // i want to get 1, because two 1 vs one 0
// other example
$allValue = array(0,0,0,1,1); // I want to get 0, because three 0 vs two 1
// other example
$allValues = array(0,1); // I want to get 0, because one 0 vs one 1 is 50:50 but 0 is first value
Sorry for my bad english.
<?php
$allValues = array(0,1,1);
$result=array_count_values($allValues); // Count occurrences of everything
arsort($result); // Sort descending order
echo key($result); // Pick up the value with highest number
?>
Edit: I've used key() because you are interested in knowing the value which has most number of occurrences and not the number itself. If you just need the number you can remove key() call.
Fiddle
try this
$allValues = array(0,0,0,1,1);
$count = array_count_values($allValues);
echo $val = array_search(max($count), $count);
Works only with 0s and 1s
function evaluateArray($array) {
$zeros = 0;
$ones = 0;
foreach($array as $item) {
if($item == 0) {
$zeros++;
} else {
$ones++;
}
}
// Change this if you want to return 1 if the result is equal
// To return ($ones >= $zeros) ? 1 : 0;
return ($zeros >= $ones) ? 0 : 1;
}
Try this:
function find_value($array) {
$zeros = 0;
$ones = 0;
for($i = 0; $i < count($array); $i++) {
($array[$i] == 0) ? $zeros++ : $ones++;
}
if($zeros == $ones) return $array[0];
return ($zeros > $ones) ? 0 : 1;
}
you can use array_count_values β Counts all the values of an array
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output
Array
(
[1] => 2
[hello] => 2
[world] => 1
)