-1

I have empty array $one and $two

$one = [];
$two = [];

I have an array named alpabhet.

$alphabet = ["A", "B", "C", "D"];

Is it posible to get the array like this:

$one = [
    0 => "A",
    1 => "C",
];

$two = [
    0 => "B",
    1 => "D",
];

Thanks!

3
  • What have you tried so far and what specific errors/issues are you getting? Commented Jul 16, 2019 at 10:03
  • @I.TDelinquent Is it possible to get the $alpabhet by 2 and store it to another array? Sorry Im new in php Commented Jul 16, 2019 at 10:05
  • 3
    PD: stackoverflow.com/questions/12405264/… Commented Jul 16, 2019 at 10:07

3 Answers 3

1

You might use the modulo % operator:

$alphabet = ["A", "B","C","D"];
$one = [];
$two = [];

foreach ($alphabet as $k => $v) {
    $k % 2 === 0 ? $one[] = $v : $two[] = $v;
}

print_r($one);
print_r($two);

Result

Array
(
    [0] => A
    [1] => C
)
Array
(
    [0] => B
    [1] => D
)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_filter() and see if the key is even or odd. Use the constant ARRAY_FILTER_USE_KEY to pass the key-value to the callback instead of the value. This will work since the array you declared is numerically indexed, starting from 0.

$alphabet = ["A", "B","C","D"];
$one = array_filter($alphabet, function($key) {
    return !($key & 1); // Even keys
}, ARRAY_FILTER_USE_KEY);

$two = array_filter($alphabet, function($key) {
    return $key & 1; // Odd keys
}, ARRAY_FILTER_USE_KEY);

This does however preserve the original keys of the array, so if you want to get the keys reassigned, you can use array_values() on the resulting array, see https://3v4l.org/jv0Od.

3 Comments

It the same code as on the link in comment
If you're wondering if I copied the code, no I did not - this is one approach (that I wrote up myself), but I'm not surprised if others have thought of it before - as its simple and does exactly what the question was asked.
Sorry that I have not closed it immediately, but was hoping for a new approach
0

You can try to loop it like this

$alphabet = ["A", "B", "C", "D"];

$one = [];
$two = [];


foreach ($alphabet as $key => $val) {
    if($key == 0 || ($key%2) == 0) {
        $one[] = $val;
    } else {
        $two[] = $val;
    }
}

echo "<pre>";
print_r($one);
print_r($two);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.