Lets say I have two arrays like this:
$array1(one, two, three);
$array2(four, five, six);
And I want the result to be like this:
[0] -> one four
[1] -> two five
[2] -> three six
How should I do this?
You can use array_map function providing your two arrays in parameter :
<?php
$array1=Array("one", "two", "three");
$array2=Array("four", "five", "six");
$res=array_map(function($r1, $r2) {return "$r1 $r2";}, $array1, $array2);
print_r($res);
Result
Array
(
[0] => one four
[1] => two five
[2] => three six
)
try this
function array_interlace() {
$args = func_get_args();
$total = count($args);
if($total < 2) {
return FALSE;
}
$i = 0;
$j = 0;
$arr = array();
foreach($args as $arg) {
foreach($arg as $v) {
$arr[$j] = $v;
$j += $total;
}
$i++;
$j = $i;
}
ksort($arr);
return array_values($arr);
}
$array1=array('one', 'two', 'three');
$array2=array('four', 'five',' six');
print_r(array_interlace($array1,$array2));
Related
$tag=[25, 26];
$tagarray[]=[25,29,30,44,26];
I need a result of [29,30,44]. Here my main array is tagarray. and tested it with tag array. I need unmatched values from tagarray without any array function like array_diff().I want to compare both arrays and only provide the elements from tagarray which are not present in tag array.
$missings = [];
$matches = false;
for ( $i = 0; $i < count($tagarray); $i++ ) {
$matches = false;
for ($e = 0; $e < count($tag); $e++ ) {
if ( $tagarray[$i] == $tag[$e] ) $matches = true;
}
if(!$matches) array_push($missings,$tagarray[$i]);
}
dd($missings);
You need nested for loops to loop over each element of your array to filter, and for each of these elements, loop on the array containing the filters.
Since you do not want to use any of the array function, you need to use a boolean to check whether or not the index was to be filtered or not and make use of a 3rd array to store the filtered array.
Take a look:
$tag = [25, 26];
$tagarray = [25,29,30,44,26];
$filteredArray = [];
for($i = 0; $i < count($tagarray); ++$i){
$toRemove = false;
for($j = 0; $j < count($tag); ++$j){
if($tagarray[$i] == $tag[$j]){
$toRemove = true;
break;
}
}
if(!$toRemove){
$filteredArray[] = $tagarray[$i];
}
}
var_dump($filteredArray);
Output
array(3) {
[0]=>
int(29)
[1]=>
int(30)
[2]=>
int(44)
}
I would personally not choose this solution and go with Aksen's one, but since you do not want to use any array functions I assume that this is a school assignment and that you have no other choices ;)
If you don't want to use array_diff() then you can use in_array():
$res = [];
foreach($tagarray[0] as $val){
if (!in_array($val,$tag)) $res[] = $val;
}
print_r($res);
Output:
Array
(
[0] => 29
[1] => 30
[2] => 44
)
Demo
If $tagarray has more then 1 element:
$tag=[25, 26];
$tagarray[]=[25,29,30,44,26];
$tagarray[]=[25,22,11,44,26];
$res = [];
foreach($tagarray as $ind=>$tagar){
foreach($tagar as $val){
if (!in_array($val,$tag)) $res[$ind][] = $val;
}
}
Output:
Array
(
[0] => Array
(
[0] => 29
[1] => 30
[2] => 44
)
[1] => Array
(
[0] => 22
[1] => 11
[2] => 44
)
)
Demo
Third Without any inbuilt PHP array function:
$tagar_l = count($tagarray);
$tag_l = count($tag);
$tagar_0_l = count($tagarray[0]);
$res = [];
for($i = 0; $i<$tagar_l; $i++){
$res[] = $tagarray[$i];
for($j = 0; $j<$tagar_0_l; $j++){
for($k = 0; $k<$tag_l; $k++){
if ($tag[$k] === $tagarray[$i][$j]) unset($res[$i][$j]);
}
}
sort($res[$i]);
}
Demo
Via foreach loop:
$res = [];
foreach($tagarray as $ind=>$arr){
$res[] = $arr;
foreach($arr as $ind_a=>$val){
foreach($tag as $comp){
if ($comp === $val) unset($res[$ind][$ind_a]);
}
}
sort($res[$ind]);
}
Demo
I am trying to get an factorial value of each item in array by using this method but this outputs only one value
can any body help me finding where i am doing wrong?
function mathh($arr, $fn){
for($i = 1; $i < sizeof($arr); $i++){
$arr2 = [];
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value){
$x = 1;
return $x = $value * $x;
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
You're going to need a little recursion so in order to do that you need to pass the lambda function into itself by reference:
function mathh($arr, $fn){
$arr2 = []; // moved the array formation out of the for loop so it doesn't get overwritten
for($i = 0; $i < sizeof($arr); $i++){ // starting $i at 0
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value) use (&$userDefined){ // note the reference to the lambda function $userDefined
if(1 == $value) {
return 1;
} else {
return $value * $userDefined($value - 1); // here is the recursion which performs the factorial math
}
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
The output:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)
I wanted to expand on this some since you're essentially (in this case) creating an array map. This could be handy if you're doing additional calculations in your function mathh() but if all you want to do is use the lambda function to create a new array with a range you could do this (utilizing the same lambda we've already created):
$mapped_to_lambda = array_map($userDefined, range(1, 5));
print_r($mapped_to_lambda);
You will get the same output, because the range (1,5) of the mapped array is the same as your original array:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)
I want to add value to array and then I want to use these arrays in array intersect. Codes are in bellow. Where am I doing mistake?
$array =['1,2,3,4','3,4,5','2,3'];
$arr2 = [];
$common = [];
for($i=0; $i<count($array); $i++)
{
$arr1 = [];
if($i==0)
{
array_push($arr1, $array[$i]);
array_push($arr2, $array[$i]);
$common = array_intersect($arr1,$arr2);
}
else
{
array_push($arr1, $array[$i]);
$common = array_intersect($arr1,$common);
}
print_r($common);
}
Output is :
Array (
[0] => 1,2,3,4
)
Array ( )
Array ( )
I want to be this :
Array (
[0] => 1,2,3,4
)
Array(
[0] => 3,4
)
Array(
[0] => 3
)
Thanks,
Try This
<?php
$array =['1,2,3,4','3,4,5','2,3'];
$arr1 = [];
for($i=0; $i<count($array); $i++)
{
$j='arr'.$i;
$j= [];
if($i==0){
array_push($j, $array[$i]);
}
else{
$a = explode(',',$array[$i-1]);
$b = explode(',',$array[$i]);
$c = array_intersect($a,$b);
$d= implode(',',$c);
array_push($j, $d);
}
echo "<pre>"; print_r($j);
}
You are misusing array_intersect. This method does works on values in an array not on a single value. To use it the way You want You should split your values by comma and insert them as separate values. For example:
value: '1,2,3,4' should be inserted as:
$array = ['1', '2', '3', '4'];
Solution (without loops etc):
<?php
$array =['1,2,3,4','3,4,5','2,3'];
$arr1 = array();
$arr2 = array();
$common = array();
$arr1 = explode(',', $array[0]);
$arr2 = explode(',', $array[1]);
$common =array_intersect($arr1, $arr2);
print_r($common);
$arr3 = explode(',', $array[2]);
$common2 = array_intersect($common, $arr3);
print_r($common2);
?>
I have the following and would want another result.
String = A,B,C,D
Trying to get an array of
A
A,B
A,B,C
A,B,C,D
My current code
$arrayA = explode(',', $query);
$arrSize = count($arrayA);
for ($x=0; $x<$arrSize; ++$x) {
for ($y=0; $x==$y; ++$y) {
array_push($arrayB,$arrayA[$x]);
$y=0;
}
}
Here's one way to do it using array_slice:
$str = 'A,B,C,D';
$strArr = explode(',', $str);
$newArr = array();
for($i=1; $i<=sizeof($strArr); $i++)
{
$newArr[] = implode( ',' , array_slice($strArr, 0, $i) );
}
print_r($newArr);
Outputs:
Array
(
[0] => A
[1] => A,B
[2] => A,B,C
[3] => A,B,C,D
)
Online demo here.
$test="a,b,c,d,e";
$arrayA = explode(',', $test);
$res=array();
$aux=array();
foreach($arrayA as $c){
$aux[]=$c;
$res[]=$aux;
}
i have not tested yet, but i think u catch the idea ;)
What would be the most efficient way of counting the number of times a value appears inside an array?
Example Array ('apple','apple','banana','banana','kiwi')
Ultimately I want a function to spit out the percentages for charting purposes
(e.g. apple = 40%, banana = 40%, kiwi = 20%)
Just put it through array_count_values. The percentages should be easy...
$countedArray = array_count_values($array);
$total = count($countedArray);
foreach ($countedArray as &$number) {
$number = ($number * 100 / $total) . '%';
}
Use array_count_values():
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
$a = Array ('apple','apple','banana','banana','kiwi');
$b = array_count_values($a);
function get_percentage($b,$a){
$a_count = count($a);
foreach ($b as $k => $v){
$ret[$k] = $v/$a_count*100."%";
}
return $ret;
}
$c = get_percentage($b,$a);
print_r($c);