return two arrays from one

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jnorton
Forum Newbie
Posts: 6
Joined: Tue Jun 19, 2007 4:24 am

return two arrays from one

Post by jnorton »

Hey All,

I have a problem that I can't figure out and desperately need some help:

I have an array containing a month date and a post count:

Array ( [1] => 1 [4] => 3 [9] => 2 [10] => 2 [11] => 4)

What I want to do is split the array at the current month integer (9) and return 2 arrays to the left and right of the current month key i.e.

left = Array ( [1] => 1 [4] => 3)
right = Array ( [10] => 2 [11] => 4)

Any help would be greatly appreciated.

Thanks in advance,

Justin.
ahowell
Forum Newbie
Posts: 17
Joined: Mon Sep 01, 2008 9:18 pm

Re: return two arrays from one

Post by ahowell »

Code: Select all

$posts = array(
    1  => 1,
    4  => 3,
    9  => 2,
    10 => 2,
    11 => 4
);
 
 
$left  = array();
$right = array();
 
foreach ($posts as $month => $postCnt) {
    if ($month < date('n')) {
        $left[$month] = $postCnt;
    } else if ($month > date('n')) {
        $right[$month] = $postCnt;
    }
}
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: return two arrays from one

Post by Christopher »

(#10850)
jnorton
Forum Newbie
Posts: 6
Joined: Tue Jun 19, 2007 4:24 am

Re: return two arrays from one

Post by jnorton »

Thanks for your help I have solved the problem now using ahowell's approach - very good work!
Post Reply