Download the PHP package itools/smartarray without Composer
On this page you can find all versions of the php package itools/smartarray. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download itools/smartarray
More information about itools/smartarray
Files in itools/smartarray
Package smartarray
Short Description PHP Arrays with Superpowers
License MIT
Homepage https://github.com/interactivetools-com/SmartArray
Informations about the package smartarray
SmartArray: PHP Arrays with Superpowers
SmartArray enhances PHP arrays to work as both traditional arrays and chainable objects. You get all the familiar array features you know, plus powerful new methods for filtering, mapping, grouping, and handling nested data - making array operations simpler while preserving normal array syntax.
Table of Contents
- Quick Start
- Usage Examples
- Highlighting Recent Articles with position()
- Accessing Elements by Position with nth()
- Looking Up Authors by ID with indexBy()
- Organizing Books by Genre with groupBy()
- Building Safe MySQL ID Lists with pluck(), map(), and join()
- Creating Grid Layouts with isFirst(), isLast(), isMultipleOf() and chunk()
- Debugging and Help
- Method Reference
- Questions?
Quick Start
Install via Composer:
Include the Composer autoloader and SmartArray class:
Convert an array to a SmartArray:
See the Method Reference for more information on available methods.
Usage Examples
Highlighting Recent Articles with position()
The position()
method returns an element's position within its parent array (starting from 1), making it easy to give
special treatment to important items like featured articles based on their position:
Output:
Key Features:
- One-based indexing: First element is position 1
- No manual counters needed
Common Use Cases:
- Featured latest articles on news sites
- Create design elements based on position
- Top stories in categories
Accessing Elements by Position with nth()
The nth()
method provides a convenient way to access elements by their position, supporting both positive and negative
indices. This is particularly useful for accessing specific items in ordered lists like search results, leaderboards, or
recent activity feeds.
Key Features:
- Zero-based indexing:
nth(0)
returns the first element - Negative indices:
nth(-1)
returns the last element - Works with both indexed and associative arrays
Looking Up Authors by ID with indexBy()
When working with collections of records, you often need to look up specific records by their ID or another unique
field. The indexBy()
method makes this easy by creating an associative array using a specified field as the key:
Output:
Important Notes:
- If multiple records have the same key value, later records will overwrite earlier ones
- For collections with duplicate keys, use
groupBy()
instead to preserve all records- Keys are automatically converted to strings (as per PHP array key behavior)
- Missing keys in the source data will be skipped with a warning
Need to preserve duplicate keys? Consider using groupBy()
instead.
Organizing Books by Genre with groupBy()
When working with data that has multiple items sharing the same key (like books by genre, products by category, or
employees by department), groupBy()
helps organize them into logical groups while preserving all records:
Output:
Common Use Cases for groupBy():
- Products by category or manufacturer
- Employees by department or location
- Sales by region or time period
- Students by grade level or class
- Events by date or venue
- Comments by post or user
- Tasks by status or priority
Important Notes:
- Each group contains a new SmartArray of all matching records
- Original record order is preserved within groups
- Groups are created in order of first appearance
- Missing or null values in the group key will be skipped with a warning
- Use
indexBy()
instead if you only need one record per key
Building Safe MySQL ID Lists with pluck(), map(), and join()
When working with database records, you may need to create a comma-separated list of IDs for use in SQL IN
clauses.
Here's how SmartArray
simplifies this process.
Creating Grid Layouts with isFirst(), isLast(), isMultipleOf() and chunk()
SmartArray makes it easy to create grid layouts by providing methods like isFirst()
, isLast()
, and isMultipleOf()
for position-based operations. Here's a simple example creating a table layout:
Or using the chunk()
method which splits the array into smaller arrays of a specified size:
Both approaches produce the same output:
Note how special characters in the data (apostrophes, quotes, ampersands) are automatically HTML encoded by
SmartString
to prevent XSS attacks while the table structure remains intact.
See the Method Reference for more information on available methods.
Debugging and Help
SmartArray provides helpful debugging tools to inspect your data structures and explore available methods.
Debug View
Call print_r()
on any SmartArray
to see a detailed view of its structure:
The output shows the nested structure and metadata for each level:
Interactive Help
Need a quick reference? Call help()
on any SmartArray
object to see available methods
and usage examples:
Method Reference
Category | Method | Description |
---|---|---|
Basic Usage | SmartArray::new($array) | Creates a new SmartArray from a regular PHP array. All nested arrays and values are converted to SmartArray and SmartString objects |
toArray() | Converts a SmartArray back to a standard PHP array, converting all nested SmartArray and SmartString objects back to their original values |
|
Array Information | count() | Returns the number of elements |
isEmpty() | Returns true if SmartArray contains no elements |
|
isNotEmpty() | Returns true if SmartArray contains any elements |
|
isFirst() | Returns true if this is the first element in its parent SmartArray |
|
isLast() | Returns true if this is the last element in its parent SmartArray |
|
position() | Gets this element's position in its parent SmartArray (starting from 1) |
|
isMultipleOf($value) | Returns true if this element's position is a multiple of $value (useful for grids) | |
Value Access | [$key] | Get a value using array syntax, e.g., $array['key'] |
->key | Get a value using object syntax, e.g., $array->key |
|
get($key) | Alternative method to get a value, e.g., $array->get($key) |
|
first() | Get the first element | |
last() | Get the last element | |
nth($index) | Get element by position, starting at 0, e.g., ->nth(0) first, ->nth(1) second, ->nth(-1) last |
|
Array Transformation | keys() | Get just the keys as a new SmartArray , e.g., ['id', 'name', 'email'] |
values() | Get just the values as a new SmartArray , discarding the keys |
|
unique() | Get unique values (removes duplicates, preserves keys) | |
sort() | Sort elements in ascending order | |
sortBy($column) | Sort elements by a specific column | |
indexBy($column) | For nested arrays, create a new SmartArray using a column as the key, e.g., indexBy('id') . Duplicates use latest value. |
|
groupBy($column) | Like indexBy() but returns values as a SmartArray to preserve duplicates. e.g., $usersByCity = $users->groupBy('city') |
|
join($separator) | Combine values into a SmartString , e.g., $users->pluck('id')->join(', ') creates "23, 51, 72" |
|
map($callback) | Transform each element using a callback function, returning a new SmartArray . The callback function receives the original value or array as an argument for each element |
|
pluck($key) | Extract one column from a nested SmartArray , e.g., $users->pluck('name') returns a SmartArray with all names |
|
chunk($size) | Returns a SmartArray of smaller SmartArray s of the specified size (for grid layouts) |
|
Debugging and Help | ||
help() | Displays help information about available methods |
See Also: For working with SmartArray
values, check out the included companion
library SmartString
, all SmartArray
values are SmartString
objects with
automatic HTML encoding and chainable methods:
https://github.com/interactivetools-com/SmartString?tab=readme-ov-file#method-reference
Questions?
This library was developed for CMS Builder, post a message in our "CMS Builder" forum here: https://www.interactivetools.com/forum/