1. <?php
  2. /**
  3. * Compacts output of queues for an experiment, handling edge cases.
  4. *
  5. * @param array $queue An array representing the queue of items.
  6. * @param string $prefix A string to prepend to each output line.
  7. * @param int $max_lines Maximum number of lines to output. Prevents runaway output.
  8. * @return string Compacted output string.
  9. */
  10. function compactQueueOutput(array $queue, string $prefix = '', int $max_lines = 100): string
  11. {
  12. $output = '';
  13. $line_count = 0;
  14. foreach ($queue as $item) {
  15. //Handle potential null or undefined item values.
  16. if ($item === null || $item === undefined) {
  17. $output .= $prefix . "Null/Undefined item\n";
  18. } else {
  19. $output .= $prefix . print_r($item, true) . "\n"; //Use print_r for complex data structures
  20. }
  21. $line_count++;
  22. if ($line_count >= $max_lines) {
  23. $output .= "\n... (truncated after $max_lines lines)\n"; // Indicate truncation
  24. break; // Stop processing if max lines reached.
  25. }
  26. }
  27. return $output;
  28. }
  29. //Example Usage (for testing)
  30. if (isset($_SERVER['argv'][1])) {
  31. $queue = ['item1', 'item2', null, 'item4', ['a', 'b'], 'item6', 'item7', 'item8', 'item9', 'item10', 'item11', 'item12', 'item13', 'item14', 'item15'];
  32. $prefix = 'Experiment Data: ';
  33. $max_lines = 5;
  34. echo compactQueueOutput($queue, $prefix, $max_lines) . "\n";
  35. }
  36. ?>

Add your comment