Zap
Documentation / Utilities

ArrayEngine

Transform and inspect arrays with a chainable API. Use ArrayEngine in controller actions to prepare response or view data, or in models to summarize and shape records returned by your data layer.

Create and inspect an ArrayEngine

Construct it with an array, or create an empty instance and call set(). Transform methods such as map(), filter(), and sortBy() update the current instance and return it for chaining. all() and final() return the resulting array.

use Zap\Core\Utils\ArrayEngine;

$numbers = (new ArrayEngine([1, 2, 3]))
 ->map(static fn (int $number): int => $number * 10)
 ->all();

// [10, 20, 30]

Use inspection methods such as count(), isEmpty(), has(), get(), first(), and last() when you need a value rather than another transformed collection.

Use it in a controller action

An action can use ArrayEngine to filter and order data before returning JSON or passing it to a view. Here the example starts with an array of products; in an application, this data may come from a model or service.

use Zap\Core\Http\Response;
use Zap\Core\Utils\ArrayEngine;

public function index(): Response
{
 $products = [
 ['name' => 'Keyboard', 'category' => 'hardware', 'active' => true, 'price' => 80],
 ['name' => 'Monitor', 'category' => 'hardware', 'active' => false, 'price' => 240],
 ['name' => 'Mouse', 'category' => 'accessories', 'active' => true, 'price' => 25],
 ];

 $visibleProducts = (new ArrayEngine($products))
 ->whereStrict('active', true)
 ->sortBy('name')
 ->all();

 return $this->json(['products' => $visibleProducts]);
}

For a rendered page, pass the resulting array in the data argument to $this->view() instead of returning JSON.

Use it in a model

A model can encapsulate array transformations that belong with its data. This example accepts rows from the model's data source, calculates totals, and groups the rows by category. Each calculation starts from a fresh engine because transformations mutate their instance.

namespace Zap\App\Models;

use Zap\Core\Base\BaseModel;
use Zap\Core\Utils\ArrayEngine;

class ProductModel extends BaseModel
{
 public function summary(array $products): array
 {
 return [
 'count' => (new ArrayEngine($products))->count(),
 'total' => (new ArrayEngine($products))->sum('price'),
 'byCategory' => (new ArrayEngine($products))
 ->groupBy('category')
 ->all(),
 ];
 }
}

The controller can call the application model with Zap's model helper and include its result in the response:

$summary = $this->model('ProductModel')->summary($products);

return $this->json(['summary' => $summary]);

Method reference

Select and filter keys or rows

  • only($keys) keeps the listed top-level keys; except($keys) removes them. Prefer only() when shaping data for an API response, so newly added internal fields are not exposed by default.
  • where($key, $value) filters rows with loose comparison; whereStrict($key, $value) uses strict comparison.
  • whereIn($key, $values) keeps matching rows; whereNotIn($key, $values) removes matches.
  • filter($callback) keeps callback matches; with no callback, it removes falsey values. reject($callback) keeps values the callback rejects.
  • pluck($key) extracts a column; groupBy($keyOrCallback) groups rows; keyBy($key) indexes rows by a field.
$names = (new ArrayEngine($products))
 ->whereIn('category', ['hardware', 'accessories'])
 ->pluck('name')
 ->sort()
 ->all();

Keep or remove selected fields

Both methods work on the collection's top-level keys and return a chainable engine. In this example, only() explicitly allowlists response fields; use except() when removing a known set of fields from a trusted structure. Neither method replaces authorization or output escaping.

$publicUser = (new ArrayEngine($user))
 ->only(['id', 'name', 'email'])
 ->all();

$publicSettings = (new ArrayEngine($settings))
 ->except(['internal_note', 'secret'])
 ->all();

Build and transform collections

  • set($array) replaces the contents; add($key, $value), push(...$values), and prepend($value) add values.
  • merge(...$arrays) merges arrays; replace($array) replaces matching keys; removeKey($key) and removeValue($value, $strict) remove entries; clear() empties the engine.
  • map($callback) transforms values; each($callback) invokes a callback without changing values; flatten() flattens nested arrays.
  • unique($flags), reverse(), slice($offset, $length), chunk($size), flip(), diff($array), and intersect($array) provide common array transformations.
  • sanitize() recursively trims strings and strips tags; trim(), lowercase(), and uppercase() recursively change string values.

Sort and inspect

  • sort(), rsort(), and ksort() sort values or keys; sortBy($key) and sortDescBy($key) sort rows by a field; shuffle() randomizes order.
  • keys() and values() replace the current contents with keys or values; implode($separator) returns a string.
  • count(), isEmpty(), has($key), get($key, $default), first(), last(), contains($value, $strict), search($value, $strict), and random() inspect or retrieve values.
  • final() and all() return the current array.

Read and write nested values

Use dot-separated paths with getDot() and setDot() to access nested arrays. getDot() returns its default when a path segment is missing; setDot() creates intermediate arrays as needed and returns the engine for chaining.

$settings = new ArrayEngine([
 'mail' => ['host' => 'smtp.example.com'],
]);

$host = $settings->getDot('mail.host', 'localhost');
$settings->setDot('mail.port', 587);

// $host is 'smtp.example.com'
// $settings->all()['mail']['port'] is 587

Find, validate, and aggregate

  • find($callback) returns the first matching value; findKey($callback) returns its key.
  • some($callback), every($callback), and none($callback) return boolean checks; partition($callback) returns two arrays: matches and non-matches.
  • reduce($callback, $initial) reduces values to one result; sum($key), avg($key), min($key), and max($key) aggregate values, optionally using a row field.
  • equal($array) checks loose array equality; identical($array) checks strict equality.

Unless noted as returning a scalar or array, transformations return the same ArrayEngine instance. They mutate its contents, so create a new instance when you need independent transformations.

Choose the right layer

  • Use ArrayEngine in a controller for presentation-specific shaping of already-fetched data.
  • Use it in a model for transformations and summaries that belong to that model's data.
  • Use database queries for filtering and aggregation over large datasets; do not load an entire table just to process it in PHP.
  • Remember that chainable transformations mutate the current ArrayEngine instance.
  • Do not treat sanitize() as validation, authorization, or context-aware output escaping.