PHP multiply each value in the array by an additional argument - php

I was trying to create a PHP function that multiplies the values/content of the array by a given argument.
Modify this function so that you can pass an additional argument to this function.
The function should multiply each value in the array by this additional argument
(call this additional argument 'factor' inside the function).
For example say $A = array(2,4,10,16). When you say
$B = multiply($A, 5);
var_dump($B);
this should dump B which contains [10, 20, 50, 80 ]
Here's my code so far:
$A = array(2, 4, 10, 16);
function multiply($array, $factor){
foreach ($array as $key => $value) {
echo $value = $value * $factor;
}
}
$B = multiply($A, 6);
var_dump($B);
Any idea? Thanks!

Your function is not right, It has to return that array and not echo some values.
function multiply($array, $factor)
{
foreach ($array as $key => $value)
{
$array[$key]=$value*$factor;
}
return $array;
}
Rest is fine.
Fiddle
You can even do this with array_map
$A = array(2, 4, 10, 16);
print_r(array_map(function($number){return $number * 6;}, $A));
Fiddle

A simpler solution where you don't have to iterate over the array yourself but instead use php native functions (and a closure):
function multiply($array, $factor) {
return array_map(function ($x) {return $x * $factor}, $array);
}

$myArray = [2, 3, 5];
$factor = 3;
array_walk($myArray, function(&$v) use($factor) {$v *= $factor;});
// $myArray = [6, 9, 15];
or like this if no $factor variable requared
array_walk($myArray, function(&$v) {$v *= 3;});

$A = array(2, 4, 10, 16);
function multiply($array, $factor){
foreach ($array as $key => $value) {
$val[]=$value*$factor;
}
return $val;
}
$B = multiply($A, 6);
var_dump($B);

Related

How to sum array using function in PHP

I got exercise to do.
Need to create a function called sumArray() that should take an array as argument and return the sum of all items in the array. Answer with a call to the function using the array: [4,256,5,13,1].Write your code below and put the answer into the variable ANSWER.
So long I came but it doesn't work.
function sumArray($array) {
$total = 0;
foreach ($array as $value) {
$total += $value;
}
return $array;
}
$ANSWER = sumArray(4, 256, 5, 13, 1);
So close. Just 2 things to do.
function sumArray($array) {
$total = 0;
foreach ($array as $value) {
$total += $value;
}
//YOU NEED TO RETURN $total !! not $array
return $total;
}
//the params given to sumArray() are not an array. just encapsule that in [] like:
$ANSWER = sumArray([4, 256, 5, 13, 1]);
First of all you need to return $total, you are again returning your array.
Second, you must need to pass array in function argument as:
$sumArray = array(4, 256, 5, 13, 1); // your array
$myAnswer = sumArray($sumArray); // calling function
Example:
<?php
function sumArray($array) {
$total = 0;
foreach ($array as $value) {
$total += $value;
}
return $total;
}
/** Your array **/
$sumArray = array(4, 256, 5, 13, 1);
/** Calling function **/
$myAnswer = sumArray($sumArray);
/** Your result **/
echo $myAnswer; //279 result
?>
You can just use PHP's built in array_sum method.
http://php.net/manual/en/function.array-sum.php
$ANSWER = array_sum(array(4, 256, 5, 13, 1));
If you must create a function then wrap it.
function sumArray($array) {
return array_sum($array);
}
$ANSWER = sumArray(array(4, 256, 5, 13, 1));
Note. In your example you haven't provided an array you have various arguments. You could also do that like so:
function sumArray() {
return array_sum(func_get_args());
}
$ANSWER = sumArray(4, 256, 5, 13, 1);
Edit. As this answer got down voted for not providing an example on how to add it up here it is. Though you should always use the built in function if it's a available and teaching you to avoid it is counterintuitive.
function sumArray($array) {
for($i = 0, $total = 0; $i < count($array); $total+=$array[$i++]);
return $total;
}
$ANSWER = sumArray([4, 256, 5, 13, 1]);
Since you need to write a function, your code should look like this:
function sumArray($array) {
$total = 0;
foreach ($array as $value) {
$total += $value;
}
return $total;
}
$ANSWER = sumArray(array(4, 256, 5, 13, 1));
Your code isn't working because you're not passing an array to the function, and you're also returning the parameter and not the $total variable.
Alternatively, you can use array_sum inside a function of your own.

PHP array doubling digits

I have an array and I want to double it but after executing the array doesn't change how to correct it as minimally as possible.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
Your values didn't double because you're not saying the key should be overwritten in $arr this code should be working:
$arr = array(1,2,3,4);
foreach($arr as $key => $value){
$arr[$key] = $value*2;
}
An alternative would be to use array_map().
<?php
function double($i){
return $i*2;
}
$arr = array(1, 2, 3, 4);
$arr = array_map('double', $arr);
var_dump($arr);
?>
You need to double the actual array $arr element, not just the value in the cycle.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
$arr[$key] = $value * 2;
}
?>
You are using a variable $value which is assigning in each for loop so this value stored in $value is overwrithing in your foreach loop. You have
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
This will work
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
print_r($arr);
?>
short solution, and supported in < PHP 5.3, try this code
<?php
$arr = array(1, 2, 3, 4);
$arr = array_map(create_function('$v', 'return $v * 2;'), $arr);
print_r($arr);
DEMO
Try the following code:
$arr = array(1, 2, 3, 4);
array_walk($arr, function(&$item){
$item*=2;
});
var_dump($arr);

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 array_filter with arguments

I have the following code:
function lower_than_10($i) {
return ($i < 10);
}
that I can use to filter an array like this:
$arr = array(7, 8, 9, 10, 11, 12, 13);
$new_arr = array_filter($arr, 'lower_than_10');
How can I add arguments to lower_than_10 so that it also accepts the number to check against? Like, if I have this:
function lower_than($i, $num) {
return ($i < $num);
}
how to call it from array_filter passing 10 to $num or whatever number?
if you are using php 5.3 and above, you can use closure to simplify your code:
$NUM = 5;
$items = array(1, 4, 5, 8, 0, 6);
$filteredItems = array_filter($items, function($elem) use($NUM){
return $elem < $NUM;
});
As an alternative to #Charles's solution using closures, you can actually find an example in the comments on the documentation page. The idea is that you create an object with the desired state ($num) and the callback method (taking $i as an argument):
class LowerThanFilter {
private $num;
function __construct($num) {
$this->num = $num;
}
function isLower($i) {
return $i < $this->num;
}
}
Usage (demo):
$arr = array(7, 8, 9, 10, 11, 12, 13);
$matches = array_filter($arr, array(new LowerThanFilter(12), 'isLower'));
print_r($matches);
As a sidenote, you can now replace LowerThanFilter with a more generic NumericComparisonFilter with methods like isLower, isGreater, isEqual etc. Just a thought — and a demo...
In PHP 5.3 or better, you can use a closure:
function create_lower_than($number = 10) {
// The "use" here binds $number to the function at declare time.
// This means that whenever $number appears inside the anonymous
// function, it will have the value it had when the anonymous
// function was declared.
return function($test) use($number) { return $test < $number; };
}
// We created this with a ten by default. Let's test.
$lt_10 = create_lower_than();
var_dump($lt_10(9)); // True
var_dump($lt_10(10)); // False
var_dump($lt_10(11)); // False
// Let's try a specific value.
$lt_15 = create_lower_than(15);
var_dump($lt_15(13)); // True
var_dump($lt_15(14)); // True
var_dump($lt_15(15)); // False
var_dump($lt_15(16)); // False
// The creation of the less-than-15 hasn't disrupted our less-than-10:
var_dump($lt_10(9)); // Still true
var_dump($lt_10(10)); // Still false
var_dump($lt_10(11)); // Still false
// We can simply pass the anonymous function anywhere that a
// 'callback' PHP type is expected, such as in array_filter:
$arr = array(7, 8, 9, 10, 11, 12, 13);
$new_arr = array_filter($arr, $lt_10);
print_r($new_arr);
if you need multiple parameters to be passed to the function, you may append them to the use statement using ",":
$r = array_filter($anArray, function($anElement) use ($a, $b, $c){
//function body where you may use $anElement, $a, $b and $c
});
In extension to jensgram answer you can add some more magic by using the __invoke() magic method.
class LowerThanFilter {
private $num;
public function __construct($num) {
$this->num = $num;
}
public function isLower($i) {
return $i < $this->num;
}
function __invoke($i) {
return $this->isLower($i);
}
}
This will allow you to do
$arr = array(7, 8, 9, 10, 11, 12, 13);
$matches = array_filter($arr, new LowerThanFilter(12));
print_r($matches);
Worth noting that since PHP 7.4 arrow functions are available, and this can be done even more neatly:
$max = 10;
$arr = array(7, 8, 9, 10, 11, 12, 13);
$new_arr = array_filter($arr, fn ($n) => $n < $max);
class ArraySearcher{
const OPERATOR_EQUALS = '==';
const OPERATOR_GREATERTHAN = '>';
const OPERATOR_LOWERTHAN = '<';
const OPERATOR_NOT = '!=';
private $_field;
private $_operation;
private $_val;
public function __construct($field,$operation,$num) {
$this->_field = $field;
$this->_operation = $operation;
$this->_val = $num;
}
function __invoke($i) {
switch($this->_operation){
case '==':
return $i[$this->_field] == $this->_val;
break;
case '>':
return $i[$this->_field] > $this->_val;
break;
case '<':
return $i[$this->_field] < $this->_val;
break;
case '!=':
return $i[$this->_field] != $this->_val;
break;
}
}
}
This allows you to filter items in multidimensional arrays:
$users = array();
$users[] = array('email' => 'user1#email.com','name' => 'Robert');
$users[] = array('email' => 'user2#email.com','name' => 'Carl');
$users[] = array('email' => 'user3#email.com','name' => 'Robert');
//Print all users called 'Robert'
print_r( array_filter($users, new ArraySearcher('name',ArraySearcher::OPERATOR_EQUALS,'Robert')) );

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