Created
July 17, 2015 18:14
-
-
Save andrewhathaway/b7fc59f9a7f7ce6a2078 to your computer and use it in GitHub Desktop.
Awray - Extremely simple PHP wrapper that makes arrays a little nicer to work with. I just wanted it to be chainable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* I just wanted PHP to be more like JavaScript, a smidge. :( | |
* | |
* *goes back to JS* | |
*/ | |
class Awray | |
{ | |
private $original = []; | |
private $array = []; | |
public function __construct($array = []) | |
{ | |
$this->original = $array; | |
$this->array = $array; | |
} | |
public function add($item) | |
{ | |
$this->array[] = $item; | |
return $this; | |
} | |
public function set($key, $item) | |
{ | |
$this->array[$key] = $item; | |
return $this; | |
} | |
public function get($key) | |
{ | |
if (!isset($this->array[$key])) { | |
return null; | |
} | |
return $this->array[$key]; | |
} | |
public function map($callback) | |
{ | |
$this->array = array_map($callback, $this->array); | |
return $this; | |
} | |
public function filter($callback) | |
{ | |
$this->array = array_filter($this->array, $callback); | |
return $this; | |
} | |
public function chunk($chunkSize = 1) | |
{ | |
$this->array = array_chunk($this->array, $chunkSize); | |
return $this; | |
} | |
public function each($callback) | |
{ | |
foreach ($this->array as $key => $value) { | |
if (is_array($value)) { | |
$value = new Awray($value); | |
} | |
$callback($key, $value); | |
} | |
return $this; | |
} | |
public function usort($callback) | |
{ | |
usort($this->array, $callback); | |
return $this; | |
} | |
public function uksort($callback) | |
{ | |
uksort($this->array, $callback); | |
return $this; | |
} | |
public function copy() | |
{ | |
return new Awray($this->array); | |
} | |
public function count() | |
{ | |
return count($this->array); | |
} | |
public function reset() | |
{ | |
$this->array = $this->original; | |
return $this; | |
} | |
public function getOriginal() | |
{ | |
return $this->original; | |
} | |
public function value() | |
{ | |
return $this->array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment