I have this array:
$array = array(a, b, c, d, e, f, g);
I want to split it in two arrays depending if the index is even or odd, like this:
$odd = array(a, c, e, g);
$even = array(b, d, f);
Thanks in advance!
One solution, using anonymous functions and array_walk:
$odd = array();
$even = array();
$both = array(&$even, &$odd);
array_walk($array, function($v, $k) use ($both) { $both[$k % 2][] = $v; });
This separates the items in just one pass over the array, but it's a bit on the "cleverish" side. It's not really any better than the classic, more verbose
$odd = array();
$even = array();
foreach ($array as $k => $v) {
if ($k % 2 == 0) {
$even[] = $v;
}
else {
$odd[] = $v;
}
}
Use array_filter (PHP >= 5.6):
$odd = array_filter($array, function ($input) {return $input & 1;}, ARRAY_FILTER_USE_KEY);
$even = array_filter($array, function ($input) {return !($input & 1);}, ARRAY_FILTER_USE_KEY);
I am not sure if this is the most elegant way, but it should work a charm:
$odd=array();
$even=array();
$count=1;
foreach($array as $val)
{
if($count%2==1)
{
$odd[]=$val;
}
else
{
$even[]=$val;
}
$count++;
}
As an almost-one-liner, I think this will be my favourite:
$even = $odd = array();
foreach( $array as $k => $v ) $k % 2 ? $odd[] = $v : $even[] = $v;
Or for a tiny little more? speed:
$even = $odd = array();
foreach( $array as $k => $v ) ( $k & 1 ) === 0 ? $even[] = $v : $odd[] = $v;
A bit more verbose variant:
$both = array( array(), array() );
// or, if $array has at least two elements:
$both = array();
foreach( $array as $k => $v ) $both[ $k % 2 ][] = $v;
list( $even, $odd ) = $both;
With array_chunk:
$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk ){
list( $even[], $odd[] ) = isset( $chunk[1]) ? $chunk : $chunk + array( null, null );
// or, to force even and odd arrays to have the same count:
list( $even[], $odd[] ) = $chunk + array( null, null );
}
If $array is guaranteed to have even number of elements:
$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk )
list( $even[], $odd[] ) = $chunk;
PHP 5.5.0+ with array_column:
$chunks = array_chunk( $array, 2 );
$even = array_column( $chunks, 0 );
$odd = array_column( $chunks, 1 );
Something similar for older PHP versions.
The keys will be 0,2,4,… and 1,3,5,…. If you don't like this, apply an array_values too:
$even = array_intersect_key( $array, array_flip( range( 0, count( $array ), 2 )));
$odd = array_intersect_key( $array, array_flip( range( 1, count( $array ), 2 )));
or
$even = array_intersect_key( $array, array_fill_keys( range( 0, count( $array ), 2 ), null ));
$odd = array_intersect_key( $array, array_fill_keys( range( 1, count( $array ), 2 ), null ));
One more functional solution with array_chunk and array_map. The last line removes empty item from the 2nd array, when size of a source array is odd
list($odd, $even) = array_map(null, ...array_chunk($ar,2));
if(count($ar) % 2) array_pop($even);
Just loop though them and check if the key is even or odd:
$odd = array();
$even = array();
foreach( $array as $key => $value ) {
if( 0 === $key%2) { //Even
$even[] = $value;
}
else {
$odd[] = $value;
}
}
One
$odd = $even = array();
for ($i = 0, $l = count($array ); $i < $l;) { // Notice how we increment $i each time we use it below, by two in total
$even[] = $array[$i++];
if($i < $l)
{
$odd[] = $array[$i++];
}
}
Two
$odd = $even = array();
foreach (array_chunk($array , 2) as $chunk) {
$even[] = $chunk[0];
if(!empty( $chunk[1]))
{
$odd[] = $chunk[1];
}
}
Based on #Jon's second variant, I made this following for use with PHP Smarty v3 template engine. This is for displaying news/blog with both one or two columns template model.
After the MySql query I'll do the following code :
if(sizeof($results) > 0) {
$data = array();
foreach($results as $k => $res) {
if($k % 2 == 0) {
$res["class"] = "even";
$data["all"][] = $data["even"][] = $res;
}
else {
$res["class"] = "odd";
$data["all"][] = $data["odd"][] = $res;
}
}
}
I obtain an array of 3 sub-arrays (including odd/even class) with Smarty syntax of use :
all items {foreach $data.all as $article}...{/foreach}
odd items only {foreach $data.odd as $article}...{/foreach}
even items only {foreach $data.even as $article}...{/foreach}
Hope it helps some people...
$odd = [];
$even = [];
while (count($arr)) {
$odd[] = array_shift($arr);
$even[] = array_shift($arr);
}
<?php
$array1 = array(0,1,2,3,4,5,6,7,8,9);
$oddarray = array();
$evenarray = array();
$count = 1;
echo "Original: ";
foreach ($array1 as $value)
{
echo "$value";
}
echo "<br> Even: ";
foreach ($array1 as $print)
{
if ($count%2==1)
{
$evenarray = $print;
echo "$print";
}
$count++;
}
echo "<br> Odd: ";
foreach ($array1 as $print2) {
if ($count%2!=1)
{
$oddarray[] = $print2;
echo "$print2";
}
$count++;
}
?>
Output:
Original: 0123456789
Even: 02468
Odd: 13579
Related
I want to compare two strings (variable1 and variable2) and i want to remove the matching characters from both strings(Only once).
For example: Variable1 : Apple, Variable2 : Ball
I tried using
array_diff(str_split('ball'), str_split('apple'))
but i got only
b (it removed all matching characters.)
Expected Output is
bl (letters A,L(only once) removed from the second strings.)
ppe (letters A,L(only once) removed from the first strings.)
How to remove the characters only once ?
You need to do workaround for this using foreach() like below:-
$array1 = str_split(strtolower($variable1));
$array2 = str_split(strtolower($variable2));
if(count($array1) >= count($array2)){
foreach($array1 as $key=>$arr){
foreach($array2 as $k=>$arr2){
if($arr == $arr2){
unset($array1[$key]);
unset($array2[$k]);
break;
}
}
}
}
if(count($array2) >= count($array1)){
foreach($array2 as $key=>$arr){
foreach($array1 as $k=>$arr1){
if($arr == $arr1){
unset($array2[$key]);
unset($array1[$k]);
break;
}
}
}
}
print_r($array1);
print_r($array2);
Output:- https://3v4l.org/dp0ui
You can handle this through for-each
$a = 'ball';
$b = 'apple';
$arr1 = str_split($a);
$arr2 = str_split($b);
$firstArr = ( count($arr1) > count($arr2) ) ? $arr2 : $arr1;
$secondArr = ( count($arr1) < count($arr2) ) ? $arr2 : $arr1;
$objSecondArray = [];
$res = [];
foreach ($secondArr as $value) {
$objSecondArray[$value] = 1;
}
foreach( $firstArr as $val ){
if(array_key_exists($val, $objSecondArray) && $objSecondArray[$val] == 1) {
$objSecondArray[$val] = null;
continue;
}
$res[] = $val;
}
print_r($res);
So I need to find the product of the even and odd numbers from the array. So far I've only managed to identify which ones are odd and which even.
<?php
$array = array('2','1','1','6','3');
foreach($array as $v){
if($v%2==0){
$even = $v;
} else{
$odd = $v;
}
}
How could I multiply the even numbers with one another (and the odd ones as well)?
First init the vars, set them to 1. The first iteration will just be 1*$v which is fine. Then use *= operator which is shorthand for $even = $even * $v;
<?php
$array = array('2','1','1','6','3');
$even = 1;
$odd = 1;
foreach($array as $v){
if($v%2==0){
$even *= $v;
} else{
$odd *= $v;
}
}
edit
Here's a '1 liner' (well, 2 if you count initing the array)
$p=array(1,1);
array_walk($array,function($v)use(&$p){$p[$v%2]*=$v;});
//$p[0] will be product of evens
//$p[1] will be product of odds
Use the *= operator
$even = 1;
$odd = 1;
foreach($array as $v){
if($v%2==0){
$even *= $v;
} else{
$odd *= $v;
}
}
function filter($values, $function) {
return array_filter(
$values,
$function
);
}
$isEven = function ($value) {
return !($value & 1);
};
$isOdd = function ($value) {
return $value & 1;
};
$data = array('2','1','1','6','3');
$odds = array_product(
filter(
$data,
$isOdd
)
);
$evens = array_product(
filter(
$data,
$isEven
)
);
array one: 1,3,5,7
array two: 2,4,6,8
the array i want would be 1,2,3,4,5,6,7,8
I'm just using numbers as examples. If it was just numbers i could merge and sort but they will be words. So maybe something like
array one: bob,a,awesome
array two: is,really,dude
should read: bob is a really awesome dude
Not really sure how to do this. Does PHP have something like this built in?
You could write yourself a function like this:
function array_merge_alternating($array1, $array2) {
if(count($array1) != count($array2)) {
return false; // Arrays must be the same length
}
$mergedArray = array();
while(count($array1) > 0) {
$mergedArray[] = array_shift($array1);
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
This function expects two arrays with equal length and merges their values.
If you don't need your values in alternating order you can use array_merge. array_merge will append the second array to the first and will not do what you ask.
Try this elegant solution
function array_alternate($array1, $array2)
{
$result = Array();
array_map(function($item1, $item2) use (&$result)
{
$result[] = $item1;
$result[] = $item2;
}, $array1, $array2);
return $result;
}
This solution works AND it doesn't matter if both arrays are different sizes/lengths:
function array_merge_alternating($array1, $array2)
{
$mergedArray = array();
while( count($array1) > 0 || count($array2) > 0 )
{
if ( count($array1) > 0 )
$mergedArray[] = array_shift($array1);
if ( count($array2) > 0 )
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
Try this function:
function arrayMergeX()
{
$arrays = func_get_args();
$arrayCount = count($arrays);
if ( $arrayCount < 0 )
throw new ErrorException('No arguments passed!');
$resArr = array();
$maxLength = count($arrays[0]);
for ( $i=0; $i<$maxLength; $i+=($arrayCount-1) )
{
for ($j=0; $j<$arrayCount; $j++)
{
$resArr[] = $arrays[$j][$i];
}
}
return $resArr;
}
var_dump( arrayMergeX(array(1,3,5,7), array(2,4,6,8)) );
var_dump( arrayMergeX(array('You', 'very'), array('are', 'intelligent.')) );
var_dump( arrayMergeX() );
It works with variable numbers of arrays!
Live on codepad.org: http://codepad.org/c6ZuldEO
if arrays contains numeric values only, you can use merge and sort the array.
<?php
$a = array(1,3,5,7);
$b = array(2,4,6,8);
$merged_array = array_merge($a,$b);
sort($merged,SORT_ASC);
?>
else use this solution.
<?php
function my_merge($array1,$array2)
{
$newarray = array();
foreach($array1 as $key => $val)
{
$newarray[] = $val;
if(count($array2) > 0)
$newarray[] = array_shift($array2)
}
return $newarray;
}
?>
hope this help
Expects both arrays to have the same length:
$result = array();
foreach ($array1 as $i => $elem) {
array_push($result, $elem, $array2[$i]);
}
echo join(' ', $result);
I have an array like the following:
array('category_name:', 'c1', 'types:', 't1')
I want the alternate values of an array to be the values of an array:
array('category_name:' => 'c1', 'types:' => 't1')
You could try: (untested)
$data = Array("category_name:","c1","types:","t1"); //your data goes here
for($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) {
$key = $data[$i];
$value = $data[$i+1];
$output[$key] = $value;
}
Alternatively: (untested)
$output = Array();
foreach($data as $key => $value):
if($key % 2 > 0) { //every second item
$index = $data[$key-1];
$output[$index] = $value;
}
endforeach;
function fold($a) {
return $a
? array(array_shift($a) => array_shift($a))
+ fold($a)
: array();
}
print_r(fold(range('a','p' )));
~)
upd: a real-life version
function fold2($a) {
$r = array();
for($n = 1; $n < count($a); $n += 2)
$r[$a[$n - 1]] = $a[$n];
return $r;
}
Here is another yet complex solution:
$keys = array_intersect_key($arr, array_flip(range(0, count($arr)-1, 2)));
$values = array_intersect_key($arr, array_flip(range(1, count($arr)-1, 2)));
$arr = array_combine($keys, $values);
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];
I have a PHP array which looks like this example:
$array[0][0] = 'apples';
$array[0][1] = 'pears';
$array[0][2] = 'oranges';
$array[1][0] = 'steve';
$array[1][1] = 'bob';
And I would like to be able to produce from this a table with every possible combination of these, but without repeating any combinations (regardless of their position), so for example this would output
Array 0 Array 1
apples steve
apples bob
pears steve
pears bob
But I would like for this to be able to work with as many different arrays as possible.
this is called "cartesian product", php man page on arrays http://php.net/manual/en/ref.array.php shows some implementations (in comments).
and here's yet another one:
function array_cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
$cross = array_cartesian(
array('apples', 'pears', 'oranges'),
array('steve', 'bob')
);
print_r($cross);
You are looking for the cartesian product of the arrays, and there's an example on the php arrays site: http://php.net/manual/en/ref.array.php
Syom copied http://www.php.net/manual/en/ref.array.php#54979 but I adapted it this to become an associative version:
function array_cartesian($arrays) {
$result = array();
$keys = array_keys($arrays);
$reverse_keys = array_reverse($keys);
$size = intval(count($arrays) > 0);
foreach ($arrays as $array) {
$size *= count($array);
}
for ($i = 0; $i < $size; $i ++) {
$result[$i] = array();
foreach ($keys as $j) {
$result[$i][$j] = current($arrays[$j]);
}
foreach ($reverse_keys as $j) {
if (next($arrays[$j])) {
break;
}
elseif (isset ($arrays[$j])) {
reset($arrays[$j]);
}
}
}
return $result;
}
I needed to do the same and I tried the previous solutions posted here but could not make them work. I got a sample from this clever guy http://www.php.net/manual/en/ref.array.php#54979. However, his sample did not managed the concept of no repeating combinations. So I included that part. Here is my modified version, hope it helps:
$data = array(
array('apples', 'pears', 'oranges'),
array('steve', 'bob')
);
$res_matrix = $this->array_cartesian_product( $data );
foreach ( $res_matrix as $res_array )
{
foreach ( $res_array as $res )
{
echo $res . " - ";
}
echo "<br/>";
}
function array_cartesian_product( $arrays )
{
$result = array();
$arrays = array_values( $arrays );
$sizeIn = sizeof( $arrays );
$size = $sizeIn > 0 ? 1 : 0;
foreach ($arrays as $array)
$size = $size * sizeof( $array );
$res_index = 0;
for ( $i = 0; $i < $size; $i++ )
{
$is_duplicate = false;
$curr_values = array();
for ( $j = 0; $j < $sizeIn; $j++ )
{
$curr = current( $arrays[$j] );
if ( !in_array( $curr, $curr_values ) )
{
array_push( $curr_values , $curr );
}
else
{
$is_duplicate = true;
break;
}
}
if ( !$is_duplicate )
{
$result[ $res_index ] = $curr_values;
$res_index++;
}
for ( $j = ( $sizeIn -1 ); $j >= 0; $j-- )
{
$next = next( $arrays[ $j ] );
if ( $next )
{
break;
}
elseif ( isset ( $arrays[ $j ] ) )
{
reset( $arrays[ $j ] );
}
}
}
return $result;
}
The result would be something like this:
apples - steve
apples - bob
pears - steve
pears - bob
oranges - steve
oranges - bob
If you the data array is something like this:
$data = array(
array('Amazing', 'Wonderful'),
array('benefit', 'offer', 'reward'),
array('Amazing', 'Wonderful')
);
Then it will print something like this:
Amazing - benefit - Wonderful
Amazing - offer - Wonderful
Amazing - reward - Wonderful
Wonderful - benefit - Amazing
Wonderful - offer - Amazing
Wonderful - reward - Amazing
foreach($parentArray as $value) {
foreach($subArray as $value2) {
$comboArray[] = array($value, $value2);
}
}
Don't judge me..
This works I think - although after writing it I realised it's pretty similar to what others have put, but it does give you an array in the format requested. Sorry for the poor variable naming.
$output = array();
combinations($array, $output);
print_r($output);
function combinations ($array, & $output, $index = 0, $p = array()) {
foreach ( $array[$index] as $i => $name ) {
$copy = $p;
$copy[] = $name;
$subIndex = $index + 1;
if (isset( $array[$subIndex])) {
combinations ($array, $output, $subIndex, $copy);
} else {
foreach ($copy as $index => $name) {
if ( !isset($output[$index])) {
$output[$index] = array();
}
$output[$index][] = $name;
}
}
}
}
#user187291
I modified this to be
function array_cartesian() {
$_ = func_get_args();
if (count($_) == 0)
return array();
$a = array_shift($_);
if (count($_) == 0)
$c = array(array());
else
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
so it returns that all-important empty array (the same result as no combinations) when you pass 0 arguments.
Only noticed this because I'm using it like
$combos = call_user_func_array('array_cartesian', $array_of_arrays);
function array_comb($arrays)
{
$result = array();
$arrays = array_values($arrays);
$sizeIn = sizeof($arrays);
$size = $sizeIn > 0 ? 1 : 0;
foreach ($arrays as $array)
$size = $size * sizeof($array);
for ($i = 0; $i < $size; $i ++)
{
$result[$i] = array();
for ($j = 0; $j < $sizeIn; $j ++)
array_push($result[$i], current($arrays[$j]));
for ($j = ($sizeIn -1); $j >= 0; $j --)
{
if (next($arrays[$j]))
break;
elseif (isset ($arrays[$j]))
reset($arrays[$j]);
}
}
return $result;
}
I had to make combinations from product options. This solution uses recursion and works with 2D array:
function options_combinations($options) {
$result = array();
if (count($options) <= 1) {
$option = array_shift($options);
foreach ($option as $value) {
$result[] = array($value);
}
} else {
$option = array_shift($options);
$next_option = options_combinations($options);
foreach ($next_option as $next_value) {
foreach ($option as $value) {
$result[] = array_merge($next_value, array($value));
}
}
}
return $result;
}
$options = [[1,2],[3,4,5],[6,7,8,9]];
$c = options_combinations($options);
foreach ($c as $combination) {
echo implode(' ', $combination)."\n";
}
Elegant implementation based on native Python function itertools.product
function direct_product(array ...$arrays)
{
$result = [[]];
foreach ($arrays as $array) {
$tmp = [];
foreach ($result as $x) {
foreach ($array as $y) {
$tmp[] = array_merge($x, [$y]);
}
}
$result = $tmp;
}
return $result;
}