PHP array doubling digits - php

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);

Related

Without built-in functions how to find differences in two arrays

I have to find the difference for both array, i have tried but i am not getting my expected.can you please help here.
<?php
$firstArray = array(3,4,5,6);
$secondArray = array(4, 5);
$outputArray = array();
foreach($firstArray as $firstArrayItem) {
foreach($secondArray as $secondArrayItem) {
if($firstArrayItem != $secondArrayItem) {
$outputArray[] = $firstArrayItem;
}
}
}
print_r($outputArray);
Expected output
[3,6]
Note: we should not use PHP inbuild functions.
a) Use a boolean value to check it:
<?php
$firstArray = array(3,4,5,6);
$secondArray = array(4, 5);
$outputArray = array();
foreach($firstArray as $firstArrayItem) {
$found = false;
foreach($secondArray as $secondArrayItem) {
if($firstArrayItem == $secondArrayItem) {
$found = true;
}
}
if($found == false){
$outputArray[] = $firstArrayItem;
}
}
print_r($outputArray);
Output: https://3v4l.org/8CuS8
b) Another way using for() loop: https://3v4l.org/9JZrW
Here is a solution that does not give a different result when the input arrays as swapped.
So it will give the same result for this:
$firstArray = array(3, 4, 5, 6);
$secondArray = array(4, 5);
as for this:
$firstArray = array(4, 5);
$secondArray = array(3, 4, 5, 6);
Also, it will deal with duplicate values as follows:
$firstArray = array(4, 4, 4);
$secondArray = array(3, 4, 6);
for which I would expect the output to be:
array(3, 4, 4, 6) // Only one 4 is common and should be excluded.
The code for having this behaviour could be (without inbuilt functions except for print_r):
$assoc = [];
foreach($firstArray as $value) {
$assoc[$value][] = 1;
}
foreach($secondArray as $value) {
$assoc[$value][] = -1;
}
foreach($assoc as $value => $list) {
$count = 0;
foreach($list as $delta) $count += $delta;
for($i = $count > 0 ? $count : -$count; $i > 0; $i--) {
$result[] = $value;
}
}
print_r($result);
$firstArray = array(3,4,5,6);
$secondArray = array(4, 5, 7);
$outputArray = diffArray($firstArray, $secondArray);
$outputArray = diffArray($secondArray, $firstArray, $outputArray);
function diffArray($arr1, $arr2, $result = array()) {
foreach($arr1 as $arr11) {
$isExist = false;
foreach($arr2 as $arr22) {
if($arr11 === $arr22) {
$isExist = true;
}
}
if(!$isExist) $result[] = $arr11;
}
return $result;
}
print_r($outputArray);

PHP multiply each value in the array by an additional argument

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);

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.

Pairwise subtraction of two arrays

There are two arrays:
$arr1 = array(1,2,3);
$arr2 = array(0,0,1);
I need to make pairwise subtraction of these two arrays. The result for arr1 - arr2 should be:
$arr3 = array(1,2,2).
Do I need to use FOR loop to to this or is there any quicker way?
In addition to the other answers, you could also use array_map()
function sub($x, $y){
return $x - $y;
}
$arr3 = array_map('sub', $arr1, $arr2);
How about this function?
function array_sub_values($arr1, $arr2)
{
$result = array();
foreach ($arr1 as $k => $val)
$result[] = $val - $arr2[$k];
return $result;
}
So you can do:
$arr1 = array(1, 2, 3);
$arr2 = array(0, 0, 1);
$arr3 = array_sub_values($arr1, $arr2);

Interchange the display order in a loop

I am trying to interchange the display order in a loop.
For example i have an array $array with values: 1,2,3,4,5 and want to display the result in the order 2,1,3,4,5.
I am using the following code for the purpose and which worked for me:
<?php
$array = array(
1,
2,
3,
4,
5,
);
$tempArray = array();
$count = 1;
foreach($array as $key => $value){
$tempArray[$key] = $value;
if(in_array($count, array(1, 2))){
if($count == 2){
echo $tempArray[1] . '<br />';
echo $tempArray[0] . '<br />';
}
}else{
echo $value . '<br />';
}
$count++;
}
But i would like to know if there is any effective (better) way of doing so?
EDIT:
$array = array(
1,
2,
3,
4,
5,
);
//Either
/*$temp = $array[1];
$array[1] = $array[0];
$array[0] = $temp;*/
//OR
list($array[1], $array[0]) = array($array[0], $array[1]);
foreach($array as $key => $value){
echo $value . '<br />';
}
Either way works fine with minimum code.
Thank you guys!
To change the display order of $array that is array(1, 2, 3, 4, 5) without changing the order of the elements in $array you need to define the display order and then display based on the display order:
$array = array(1, 2, 3, 4, 5);
$display = array_keys($array);
list($display[1], $display[0]) = array($display[0], $display[1]);
foreach ($display as $key)
{
$value = $array[$key];
printf("%d<br />\n", $value);
}
This works - as you wrote it already yourself in the comments - by switching the order (keys) of the first two elements(0 and 1, arrays are zero-based).

Categories