split array in PHP

Question

Answers ( 1 )

    0
    2024-01-11T18:05:21+00:00
    1. Using array_slice() Function: This function extracts a portion of an array. For example, if you want to split an array into chunks of a specific size, you can use array_slice() in a loop.

      $array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      $size = 3; // Size of each chunk
      
      $parts = [];
      while(count($array)) {
          $parts[] = array_slice($array, 0, $size);
          $array = array_slice($array, $size);
      }
      
      // Output the parts
      print_r($parts);
      
    2. Using array_chunk() Function: This is a simpler way to divide an array into multiple smaller arrays of a given size.

      $array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      $size = 3; // Size of each chunk
      
      $chunks = array_chunk($array, $size);
      
      // Output the chunks
      print_r($chunks);
      
    3. Using array_splice() Function: This function can also be used to split an array, but it modifies the original array.

      $array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      $size = 3; // Size of each chunk
      
      $parts = [];
      while(count($array)) {
          $parts[] = array_splice($array, 0, $size);
      }
      
      // Output the parts
      print_r($parts);
      

    Each of these methods serves the purpose of splitting an array but in slightly different ways. Choose the one that best suits your specific use case.

Leave an answer