Jump to content

Custom array_chunk()


The Little Guy

Recommended Posts

I know PHP has an array_chunk function, but how would I duplicate that function into my own function?

 

Here is what I got so far:

<?php
function chunk($array, $amt){
for($i=0;$i<count($array);$i++){
	for($c=0;$c<$amt;$c++){
		if($c%$amt){
			$tempArray[$i][$c] = $array[($i+1)];
			$i = $i + 1;
		}else{
			$tempArray[$i][$c] = $array[$i];
		}
	}
}
return $tempArray;
}


$arr = array('1','2','3','4');
print_r(chunk($arr, 2));
?>

 

Edit:

 

Forgot to say:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [2] => Array
        (
            [0] => 3
            [1] => 4
        )

)

 

See the second sub array, that should be a 1 not a 2, that is the problem I am having.

Link to comment
Share on other sites

Anyways, you are over-complicating it.  You don't need a for loop and a modulus.  You just need one or the other.  Modulus is cleaner so I'd go with that.

 

function chunk ($array, $size) {
   if (!is_array($array)) return false;

   $chunk = 0;
   $pos = 1;
   foreach ($array as $key => $val) {
      $newArray[$chunk][$key] = $val;
      if ($pos % $size == 0) $chunk++;
      $pos++;
   } // end foreach

   return $newArray;
} // end function chunk

Link to comment
Share on other sites

I need to define the sub arrays, and I cant get it...

 

Any help?

function chunk ($array, $size) {
if (!is_array($array)) return false; 
$chunk = 0;
$pos = 1;
for($i=0;$i<count($array);$i++) {
	if(chunk % amt == 0){
		$tempArray[$chunk] = array();
	}
	$newArray[$chunk][$key] = $val;
	if ($pos % $size == 0) $chunk++;
	$pos++;
} // end foreach
return $newArray;
}

Link to comment
Share on other sites

Oh do you mean define as in initialize them? 

 

function chunk ($array, $size) {
   if (!is_array($array)) return false;

   $chunk = 0;
   $pos = 1;
   foreach ($array as $key => $val) {
      if (!$newArray[$chunk]) $newArray[$chunk] = array();
      $newArray[$chunk][$key] = $val;
      if ($pos % $size == 0) $chunk++;
      $pos++;
   } // end foreach

   return $newArray;
} // end function chunk

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.