1

By definition, PHP's array_shift will return the first elem from the array and the array will downsize one.

I want to slice an array alternatingly into two sub-arrays, i.e index of 0,2,4,6,... and index of 1,3,5,7,...

I first break it into chunks of 2, then I use array_map to call array_shift. However, it is half correct (output below):

array1: Array ( [0] => greeting [1] => question [2] => response ) 
array2: Array ( [0] => Array ( [0] => greeting [1] => hello ) [1] => Array ( [0] => question [1] => how-are-you ) [2] => Array ( [0] => response [1] => im-fine ) )

Here's the code:

$a=array("greeting", "hello", "question", "how-are-you", "response", "im-fine");
$b=array_chunk($a, 2);
$c=array_map("array_shift", $b);
echo "array1: ";
print_r($c);
echo "array2: ";
print_r($b);

array2 does not seem to downsize after array_shift. Is this the correct behavior? How can I do what I intend to do?

Thanks

1

2 Answers 2

0

While this is already solved using array functions here is a low tech solution using a simple toggle to separate the odd and even elements...

$in = array("greeting", "hello", "question", "how-are-you", "response", "im-fine");

$i = 0;
$list = array();
foreach ($in as $text)
{
  $list[$i][] = $text;
  $i = 1 - $i;
}

print_r($list[0]);
print_r($list[1]);

Result...

Array ( [0] => greeting [1] => question [2] => response ) 
Array ( [0] => hello [1] => how-are-you [2] => im-fine )
Sign up to request clarification or add additional context in comments.

Comments

-2

Try this way to split your array alternatively EVEN and ODD keys, there may be many ways to do this, but this is my simple way using array_walk

$odd = [];
$even = [];
$both = [&$even, &$odd];
$array=["greeting", "hello", "question", "how-are-you", "response", "im-fine"];
array_walk($array, function($value, $key) use ($both) { $both[$key % 2][] = $value; });
print '<pre>';
print_r($even);
print_r($odd);
print '</pre>';

RESULT: Success time: 0.02 memory: 24448 signal:0

<pre>Array
(
    [0] => greeting
    [1] => question
    [2] => response
)
Array
(
    [0] => hello
    [1] => how-are-you
    [2] => im-fine
)

4 Comments

Hi, Being Human: Thanks for the suggestions. The first works and the second prints out like this: Array ( ) Array ( )
@ShuangLiang see my edited answer, as i set $array variable in my first solution, so it was not set here, that's why you get Array(), check now...
Credit where credit is due; stackoverflow.com/questions/12405264/…
@Being Human I see there is one way left. One way or the other, it counts as long as it works. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.