SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast LobsterMan's Avatar
    Join Date
    Apr 2005
    Location
    Jerusalem, Israel
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Dividing an array

    I want to create a function that will take an array and divide it in to 2 arrays, like this: if the array has lest say, 20 variables, the firs array will have 10 and the second will have 10. and if it has 19, the first array will have 10 and the second array wil have 9.
    I'm totally clueless, any help would be appreciated.

  2. #2
    SitePoint Member
    Join Date
    Dec 2005
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Mhn, whats the problem?

    First calculating the size of the array which should contain the first part of the original array using ceil to round the value up. Than getting through all elements of the array which should be splitted using foreach, having a counter in that loop (e.g. $i) which will increase with every call and than you have to check with an "if", if $i is smaller than the size of the first part. If it's true add the value to the first part, else add it to the second.


    Greetings, Floriam

  3. #3
    SitePoint Enthusiast LobsterMan's Avatar
    Join Date
    Apr 2005
    Location
    Jerusalem, Israel
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hmm, i figured i'd need to cound the array, but i wasn't femiliar with the ceil function... sounds good, i'll try that. thanks.

  4. #4
    SitePoint Addict SwordsmanX's Avatar
    Join Date
    Sep 2005
    Posts
    211
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just go with this:

    PHP Code:
    $array_of_chunked_arrays=array_chunk($my_old_array10true); 
    true means that the new array will preserve the keys

  5. #5
    SitePoint Enthusiast LobsterMan's Avatar
    Join Date
    Apr 2005
    Location
    Jerusalem, Israel
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,
    the array chunk is a great soultuion, but i'll first need to fun count(), divide by 2 and ceil() to get the number of values for each array. this makes it quite simple. thank you.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •