pquery.array.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * pQuery plugin for easily executing practical functions on arrays, in a
  4. * more object-oriented manner than natively supported by PHP.
  5. *
  6. * @package pQuery
  7. */
  8. /**
  9. * pQuery extension class for the 'array' plugin.
  10. */
  11. class pQueryArray extends pQuery {
  12. static $accepts = array('array');
  13. /**
  14. * Get the value of an array element at the given index.
  15. *
  16. * @param int|string $index The index to get the element of.
  17. * @returns mixed The array value at the given index if it exists, or NULL otherwise.
  18. */
  19. function get($index) {
  20. return isset($this->variable[$index]) ? $this->variable[$index] : null;
  21. }
  22. /**
  23. * Check if the array is empty.
  24. *
  25. * @returns bool Whether the array is empty.
  26. */
  27. function is_empty() {
  28. return !$this->count();
  29. }
  30. /**
  31. * Get the number of elements in the array.
  32. *
  33. * @returns int The number of elements.
  34. */
  35. function count() {
  36. return count($this->variable);
  37. }
  38. /**
  39. * Reverse the array.
  40. *
  41. * @returns pQueryArray The current object.
  42. */
  43. function reverse() {
  44. $this->variable = array_reverse($this->variable);
  45. return $this;
  46. }
  47. /**
  48. * Execute an existing array function on the array.
  49. *
  50. * @var $method string A (part of the) function name to execute.
  51. * @var method $args Additional arguments to pass to the called function.
  52. * @returns mixed Either the current object, or the return value
  53. * of the called array function.
  54. */
  55. function __call($method, $args) {
  56. $function = 'array_'.$method;
  57. if( function_exists($function) ) {
  58. array_unshift($args, &$this->variable);
  59. return call_user_func_array($function, $args);
  60. }
  61. if( in_array($method, array('shuffle', 'sort')) ) {
  62. $method($this->variable);
  63. return $this;
  64. }
  65. return self::error('Plugin "%s" has no method "%s".', __CLASS__, $method);
  66. }
  67. }
  68. /**
  69. * Shortcut constructor for {@link pQueryArray}.
  70. *
  71. * @returns pQueryArray A new pQueryArray instance.
  72. */
  73. function _arr($array) {
  74. return pQuery::create('array', $array);
  75. }
  76. pQuery::extend('pQueryArray', 'array');
  77. ?>