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.
Related
I would like to perform a selection sort of an array, using PHP. But instead of having it move from left to right, I would like it to move from right to left.
Example of Logic
$array = array(3, 0, 2, 5, -1, 4, 1);
function swap($data1, $a, $b) {
//Create temp storage for b
$bTmp = $data1[$b];
//Switch b for a value
$data1[$b] = $data1[$a];
//Set a as b value before switch
$data1[$a] = $bTmp;
//Return the sorted data
return $data1;
}
function selection($data)
{
$i1=count($data)-1;
$j1=$i1-1;
//For each value in the array
for($i=$i1; $i>1; $i--) {
//Set the minimum as the current position
$min = $i;
//Check the next value in the array (left)
for($j=$j1; $j>0; $j--) {
//If the original value (i) is bigger than the next value...
if ($data[$j]>$data[$min]) {
//Set the smaller value to be the next value
$min = $j;
}
}
$data = swap($data, $i, $min);
}
return $data;
}
//Perform the module using the array values and then output values with keys
echo(var_dump(selection($array)));
I have tried to incorporate this by using a decrementing for loop. But it only appears to partially sort the array.
Check this, it will work as expected
<?php
$array = array(3, 0, 2, 5, -1, 4, 1);
// $array = array(24,12,16,32,41,22);
function swap($data1, $a, $b) {
$bTmp = $data1[$b];
$data1[$b] = $data1[$a];
$data1[$a] = $bTmp;
return $data1;
}
function selection($data)
{
$i1=count($data)-1;
$j1 = $i1;
foreach($data as $key => $val){
for($i=$i1; $i>0; $i--) {
$min = $i;
$j1 = $min;
for($j=$j1; $j>=0; $j--) {
if ($data[$j]>$data[$min]) {
$data = swap($data, $j, $min);
$min = $j;
}
}
}
}
return $data;
}
echo(var_dump(selection($array)));
?>
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);
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.
Let's say I have an array like this:
$my_array = array(1, 2, 3, 4, array(11, 12, 13, 14), 6, 7, 8, array(15, 16, 17, 18), 10);
I want to build a recursive function that returns an array which contains all the even numbers from my_array. I tried something like:
function get_even_numbers($my_array)
{
$even_numbers = array();
foreach($my_array as $my_arr)
{
if(is_array($my_arr)
{
get_even_numbers($my_arr);
foreach($my_arr as $value)
{
if($value % 2 == 0)
{
$even_numbers[] = $value;
}
}
}
}
return even_numbers;
}
But it doesn't works.
Thank you
It's simple:
Check if the input you get into the function is an array.
If it is, that means you have to loop over the values of the array, and call your function (so it is recursive)
Otherwise, just check if the value coming in is even, and add it to an array to return.
That, in PHP, looks like:
function recursive_even( $input) {
$even = array();
if( is_array( $input)) {
foreach( $input as $el) {
$even = array_merge( $even, recursive_even( $el));
}
}
else if( $input % 2 === 0){
$even[] = $input;
}
return $even;
}
Unless it is a thought exercise for your own edification, implementing a recursive function isn't required for this task, which can accomplished instead by using the higher-order, built-in PHP function, array_walk_recursive.
$res = array();
array_walk_recursive($my_array, function($a) use (&$res) { if ($a % 2 == 0) { $res[] = $a; } });
Of course, this could be wrapped in a function:
function get_even_numbers($my_array) {
$res = array();
array_walk_recursive($my_array, function($a) use (&$res) { if ($a % 2 == 0) { $res[] = $a; } });
return $res;
}
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')) );