Multiplying two arrays in php - php

I have a challenge multiplying two arrays.
this is what i intend doing
Array1 ( [0] => 2 [1] => 2 )
Array2 ( [0] => 8000.00 [1] => 1234.00 )
Every time i multiply this it breaks it down into 4 and returns a result as this
Array ( [0] => 16000 [1] => 16000 [2] => 2468 [3] => 2468 )
However when i pass single a single data it gets it right.
Here is my code, i'll appreciate any help i can get. Thanks
$total = array();
foreach($office_price as $price){
foreach($office_quantity as $quantity){
$total[] = $price * $quantity;
}
}

You can give multiple arrays to array_map, and it will process the corresponding elements:
$total = array_map(function($x, $y) { return $x * $y; },
$office_price, $office_quantity);

You loop through both arrays, so you get every value twice.
As you know, an array is built up using keys and values.
Use your foreach to that extent:
$total = array();
foreach ($office_price as $key=>$price) {
$total[] = $price * $office_quantity[$key];
}
You only need to loop one array, and by using the value from the second array with the same key, you get the proper result.

Use Array map function it will works
$total_hours = array(10, 20, 30);
$hourly_rate = array(15, 10, 15);
$total_pay = array_map(function($hour, $rate) {
return $hour * $rate;
}, $total_hours, $hourly_rate);

$total_in_array = array_map(function($x, $y) { return $x * $y; }, $office_price, $office_quantity); // This will return array of multiplied numbers
$total = array_sum($total_in_array); // This will return the total

Use this
$total = array();
for($i=0;$i<count($office_price);$i++){
$total[] = $office_price[$i] * $office_quantity[$i];
}

To multiply two arrays, you must do it elementwise: no nested loops involved. For example, if you want to get $total[2], then its value is $office_price[2] * $office_quantity[2]. Thus the one foreach loop. To loop through keys, use ... as $key => $price.
$office_price = array(10, 100, 1000);
$office_quantity = array(1, 2, 3);
$total = array();
foreach($office_price as $key => $price){
$total[$key] = $price * $office_quantity[$key];
}
var_dump($total);
// array(3) { [0]=> int(10) [1]=> int(200) [2]=> int(3000) }

$a= array (2,2);
$b= array(8000,1234);
$total = array();
for ($i=0;$i<count($a);$i++) {
$total[] = $a[$i] * $b[$i];
}

function a($a, $b)
{
$r = [];
for($i = 0; $i < (count($a)); $i ++)
{
$r[] = $a[$i] * $b[$i];
}
return $r;
}

Related

array_rand - how can I get more values than array has?

I'm trying to get more random values than array has using array_rand. Is there any way to do it?
$amount = 6;
$numbers = array(
"10",
"20",
"30"
);
array_rand($numbers, $amount);
I can only get 3 values, because array has only 3 values. But what if I want to get like 6 values (of course if $qty > array has, will repeat but theres no problem)
Just use a custom solution that is not dependent on the features of array rand:
See it in action:
https://ideone.com/Kimjx4
// The quantity you want
$quantity = 6;
// the values to choose from
$numbers = array(
"10",
"20",
"30"
);
// get the keys so it will also work with associative arrays
$keys = array_keys($numbers);
// how many elements are there in our source array
$length = count($keys);
// where we store our result
$result = [];
// iterate for x quantity
for($c=0;$c < $quantity; $c++) {
// add random result from source to result array.
$result[] = $numbers[$keys[rand(0, $length-1)]];
}
var_dump($result);
if you want it as a function that also handles associative keys
https://ideone.com/SqTrKg
function getRandomResults(array $source, $quantity) {
$keys = array_keys($source);
// how many elements are there in our source array
$length = count($keys);
// where we store our result
$result = [];
// iterate for x quantity
for($c=0;$c < $quantity; $c++) {
// add random result from source to result array.
$result[] = $source[$keys[rand(0, $length-1)]];
}
return $result;
}
$res = getRandomResults([
"10",
"20",
"30"
], 6);
var_dump($res);
I'd like also to try))
function my_array_rand(array $arr, int $count): array
{
assert($count > 0);
if ($count <= count($arr)) {
return array_rand($arr, $count);
}
foreach (range(1, $count) as $index) {
$res[] = array_rand($arr, 1);
}
return $res ?? [];
}
$arr = [1,2,3,4,5,6,7];
var_dump(my_array_rand($arr, 100));

PHP Pick random array values based on total

I have array in php like
$randomarray = array('1106'=>'5','1110'=>'2','11867'=>'3','1206'=>'2','1210'=>'1','1223'=>'6','1235'=>'3','12565'=>'4','1258'=>'5','12690'=>'2','12693'=>'3','1283'=>'1','12944'=>'5');
I want to randomly pick elements from the array with the count of exactly 20. Each element have to only one time
I tried some array random example. I can't able to get the exact total which i expect.
this is the example of what i did that. But loop went to infinitive,
function randomTo($numIn) {
global $randomarray;
$numOut = 0;
$numbers = array();
do {
$key = array_rand($randomarray );
$add = $mainarray[$key];
if($numOut + $add > $numIn)
continue;
$numOut += $add;
$numbers[] = $add;
unset($mainarray[$key]);
} while( $numOut != $numIn );
return $numbers;
}
$testdata = randomTo(20);
The problem that you're trying to solve is called Subset sum and it's a subset of the Knapsack problem.
Just google for it, and while you're at it, google for Dynamic programming as it's a way of approaching the problem.
if(count($randomarray)) > 20
print_r(array_rand($randomarray, 20));
Get some Idea from this :
An example for getting random value from arrays
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[] = $arr[$i];
}
return $num == 1 ? $r[0] : $r;
}
$a = array("apple", "banana", "cherry");
print_r(array_random($a));
print_r(array_random($a, 2));
?>
cherry
Array
(
[0] => banana
[1] => apple
)
And example for getting random value from assoc arrays;
<?php
function array_random_assoc($arr, $num = 1) {
$keys = array_keys($arr);
shuffle($keys);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[$keys[$i]] = $arr[$keys[$i]];
}
return $r;
}
$a = array("a" => "apple", "b" => "banana", "c" => "cherry");
print_r(array_random_assoc($a));
print_r(array_random_assoc($a, 2));
?>
Array
(
[c] => cherry
)
Array
(
[a] => apple
[b] => banana
)

Find percentile using an array in php

I have a array like this
array(
45=>5,
42=>4.9,
48=>5,
41=>4.8,
40=>4.9,
34=>4.9,
.....
)
Here index is userid and value is his score.
Now what i want is to achieve percentile for on user for example percentile of 45,48 would be 99 and 42,40,34 would be 97 and 41 would be 94.
How i can achieve this?
Sort the array based on the "score", ascending
Percentile = (Index of an element in the sorted array ) * 100 / (total elements in the array)
Example:
<?php
$array = array(
45=>5,
42=>4.9,
48=>5,
41=>4.8,
40=>4.9,
34=>4.9,
);
print("Unsorted array:<br/>");
print_r($array);
arsort($array);
print("<br/>");
print("Sorted array:<br/>");
print_r($array);
print("<br/>");
$i=0;
$total = count($array);
$percentiles = array();
$previousValue = -1;
$previousPercentile = -1;
foreach ($array as $key => $value) {
echo "\$array[$key] => $value";
if ($previousValue == $value) {
$percentile = $previousPercentile;
} else {
$percentile = 99 - $i*100/$total;
$previousPercentile = $percentile;
}
$percentiles[$key] = $percentile;
$previousValue = $value;
$i++;
}
print("Percentiles:<br/>");
print_r($percentiles);
print("<br/>");
?>
It can be done a lot easier
function procentile($arr, $percentile=0.95){
sort($arr);
return $arr[round($percentile * count($arr) - 1.0-$percentile)];
}

Find the second highest variable in array

I would like to find the second highest variable in an array.
For example if I have:
$cookies = array(
"chocolate" => "20",
"vanilla" => "14",
"strawberry" => "18",
"raspberry" => "19",
"bluebery" => "29"
);
I can use max($cookies) to find the highest variable, which is "bluebery" => "29".
But how do I find the second highest? "chocolate" => "20"
Sort it and get the second item is the easiest way:
arsort($cookies);
$keys = array_keys($cookies);
echo $keys[1]; // chocolate
echo $cookies[$keys[1]]; // 20
If you want a more efficient way, you can also do it manually, by keeping track of both the highest and second-highest items at the same time:
function secondMax($arr) {
$max = $second = 0;
$maxKey = $secondKey = null;
foreach($arr as $key => $value) {
if($value > $max) {
$second = $max;
$secondKey = $maxKey;
$max = $value;
$maxKey = $key;
} elseif($value > $second) {
$second = $value;
$secondKey = $key;
}
}
return array($secondKey, $second);
}
Usage:
$second = secondMax($cookies);
echo "{$second[0]} => {$second[1]}"; // chocolate => 20
For fun you could use max() twice :)
For example:
Duplicate the array
Run max()
Remove the max
Run max() again
The alternative would to sort the array based on values and get the second element of the array. I'd be curious which is faster. Likely the sort.
arsort($cookies) AND array_shift($cookies) AND list($k, $v) = each($cookies);
echo "$k => $v"; // chocolate => 20
rsort($cookies);
echo $cookies[1];
Try :
asort($cookies);
end($cookies);
prev($cookies);
list($key,$value) = each($cookies);
or reverse it
arsort($cookies);
reset($cookies);
next($cookies);
list($key,$value) = each($cookies);
** Edit **
I thought I'd share this anyway, if someone would stumble across this and need it :
/**
* Returns the key => value pair with the specific rank.
* if $rank is 0, falase is returned. If $rank is positive,
* then the $rank th smallest pair is returned. If $rank
* is negative, then the $rank th biggest pair is returned.
* If $rank range is outside the size of the array, false
* is returned. If a callable function is provided, it will
* be used to sort the data. If $keySort is true, then the
* data will be sorted by keys instead (the callback functions
* will receive the keys to compare instead of values)
*
* #param $data array
* #param $rank int
* #param $cmd_function callable (optional)
* #param $keySort boolean (optional)
* #return array the key => value pair or false
*/
function findByRank($data, $rank, $cmd_function = null, $keySort = false) {
if (($rank == 0) || (abs($rank) > count($data))) {
return false;
}
$sort = ($keySort?'k':'a').'sort';
if ($cmd_function != null) {
$sort = 'u'.$sort;
$sort($data, $cmd_function);
} else {
$sort($data);
}
if ($rank > 0) {
reset($data);
$next = 'next';
} else {
end($data);
$next = 'prev';
$rank = abs($rank);
}
while (--$rank > 0) $next($data);
return each($data);
}
$cookies = array(
"chocolate" => "20",
"vanilla" => "14",
"strawberry" => "18",
"raspberry" => "19",
"bluebery" => "29"
);
header('Content-type:text/plain; charset=utf-8');
var_dump(findByRank($cookies, -10)); // -> false
var_dump(findByRank($cookies, -2)); // -> 'chocolate' key=>value pair
var_dump(findByRank($cookies, -1)); // -> 'blueberry' key=>value pair
var_dump(findByRank($cookies, 0)); // -> false
var_dump(findByRank($cookies, 1)); // -> 'vanilla' key=>value pair
var_dump(findByRank($cookies, 3)); // -> 'raspberry' key=>value pair
Sort the array descending and take the second value. Or, to be save, take the first value and go through the array until you find a smaller one.
function second_largest($arr)
{
sort($arr, SORT_NUMERIC);
return($arr[count($arr) - 2]);
}
//echo 3
echo second_largest(array(0, 3, 4, 1, 2));
Check this URL
http://maheshbokkisam.blogspot.in/2013/04/find-nth-highest-value-in-array-without.html
Find Nth/ N th highest value from given array without using any sorting in PHP
$ar = array(23,56,87,12,98,85,24,54,99,100,1,4,5,2,76,37,92);
$n = count($ar) - 5;
for($i = 0; $i < $n; $i++){
// Get the max value from array // get the Nth value from last loop
echo $a = max($ar);
echo "<br /><pre>"; print_r($ar);
$ar = array_flip($ar); // Flip the array
//print_r($ar);
unset($ar[$a]); // Unset the max value from array
//print_r($ar);
$ar = array_flip($ar); // Flip the array
echo "</pre>";
echo "<hr />";
}
<?php
// Finding Second highest number (In case of index of array is random)
$arr = [-5 => 33, -4 => -2, 8 => 0, 44, 44, 44, 44, 44];
$max = -INF;
$secondMax = -INF;
$size = sizeof($arr);
if ($size > 1) {
foreach ($arr as $key => $value) {
echo "KEY-> ", $key, "VALUE->", $value, "\n";
if ($value > $max) {
$max = $value;
} else {
if ($value < $max && $value > $secondMax) {
$secondMax = $value;
}
}
}
} else if ($size == 0) {
$max = "No Max element";
$secondMax = "No Second highest element";
} else {
foreach ($arr as $key => $value) {
$max = $arr[$key];
$secondMax = "No second highest element";
}
}
echo "maxvalue = ", $max, "\n";
echo "secondmax =", $secondMax;

How to assign a rank number to an array when ties exist

I am struggling to know where to start when trying to assign ranks to the numeric values in an array when there are ties. So, for example, I need to turn an array like the following:
myarray = (4,76,34,13,34)
into another array like:
myarray2 = (1,5,3.5,2,3.5)
Basically, when the same number occurs more than once in the array, the assigned rank to those numbers is the average of the ranks. So, instead of the two 34s being ranked 3 and 4 they both get assigned 3.5. Similarly, if there were 3 copies of 34 then the 3 assigned ranks would be divided by 3. Any help would be much appreciated!
Many thanks,
Adam
I had fun with this one!
function rank($input)
{
$output = array();
$ranking = $input; sort($ranking); $ranking = array_flip($ranking);
$last_val = -1;
foreach($ranking as $key => $val){
$repetitions = ($val-$last_val-1);
$last_val = $val;
if($repetitions) {
$ranking[$key] = (($val*($repetitions+1))-($repetitions+1)*(($repetitions)/2))/($repetitions+1)+1 ;
} else {
$ranking[$key] = $val+1;
}
}
foreach($input as $key => $val){
$output[$key] = $ranking[$val];
}
return $output;
}
Use it like this:
$a = array(4,76,34,13,34);
$c = rank($a);
print_r($c);
will output:
Array
(
[0] => 1
[1] => 5
[2] => 3.5
[3] => 2
[4] => 3.5
)
wich is the same as:
Array(1, 5, 3.5, 2, 3.5)
as expected!
Here is one way to do it.
<?php
$myarray = array(4,76,34,13,34);
$sorted_array = $myarray;
$grouped_array = array();
sort($sorted_array);
foreach ($sorted_array as $rank => $entry) {
// Initialize the entry if it doesn't already exist
if (empty($grouped_array[$entry])) {
$grouped_array[$entry]['count'] = 1.0;
$grouped_array[$entry]['total'] = $rank + 1; // Account for 0-based array
} else {
$grouped_array[$entry]['count'] += 1.0;
$grouped_array[$entry]['total'] += $rank + 1; // Account for 0-based array
}
}
$myarray2 = array();
foreach ($myarray as $entry) {
// Get the average
$myarray2[] = $grouped_array[$entry]['total'] / $grouped_array[$entry]['count'];
}
I assume you also need to handle the cases where there are three or four or n values tied at the same rank.
I'm no PHP guru, but here's an approach (pseudo code) to defining a rank function:
define a = original array
define s = a.Sorted
define rank(n) = (s.FirstIndexOf(n) + s.LastIndexOf(n)) / 2
You may need to work a few examples on paper to convince yourself that this works even for triples and higher; it's reliant on s being sorted so that duplicates are adjacent.
The accepted solution (and others too) seem to be way more complicated than they need to be:
function Rank($data) {
$count = 0;
$unique = $data; sort($unique);
$unique = array_count_values($unique);
foreach ($unique as $key => $frequency) {
foreach (range(1, $frequency) as $i) {
$unique[$key] += $count++;
}
$unique[$key] /= $frequency;
}
foreach ($data as $key => $value) {
$data[$key] = $unique[$value];
}
return $data;
}
Example (demo):
print_r(Rank(array(4, 76, 34, 13, 34))); // 1; 5; 3.5; 2; 3.5
print_r(Rank(array(4, 76, 34, 13, 34, 34))); // 1; 6; 4; 2; 4; 4

Categories