PHP code example of itools / smartarray

1. Go to this page and download the library: Download itools/smartarray library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

itools / smartarray example snippets



tools\SmartArray\SmartArray;

$records = [
    ['id' => 10, 'name' => "John O'Connor",  'city' => 'New York'],
    ['id' => 15, 'name' => 'Xena "X" Smith', 'city' => 'Los Angeles'],
    ['id' => 20, 'name' => 'Tom & Jerry',    'city' => 'Vancouver'],
];

// Always start with raw data for processing
$users = SmartArray::new($records)
    ->asHtml()          // Make values HTML-safe (or use SmartArrayHtml::new() directly)
    ->sortBy('name');   // Sort alphabetically by name


// Now $users contains SmartStrings for safe output
foreach ($users as $user) {
    echo "Name: $user->name, ";   // Automatically HTML-encoded for safety
    echo "City: $user->city\n";
}

// Values are automatically HTML-encoded in string contexts to prevent XSS (see SmartString docs for more details)
echo $users->first()->name; // Output: John O&apos;Connor

// Use chainable methods to transform data
$userIdAsCSV = $users->pluck('id')->implode(', '); // Output: "10, 20, 15"

// Easily convert back to arrays and original values
$usersArray = $users->toArray(); // Convert back to a regular PHP array and values

// Convert SmartStrings back to original values
// Note: The `value()` method returns the raw value from a `SmartString` object.
$userId = $users->first()->id->value(); // Returns 10 as an integer

// Note: If the key doesn't exist, a SmartNull object is returned instead of throwing an error, so you can chain
// safely without checking for isset() first.


$articles = [
    ['title' => 'Astronomers Photograph Distant Galaxy for First Time'],
    ['title' => 'New Species of Butterfly Found in Amazon Rainforest'],
    ['title' => 'Ocean Expedition Maps Unexplored Deep Sea Valleys'],
    ['title' => 'Ancient Star Charts Discovered in Mountain Cave'],
    ['title' => 'Rare Rainbow Clouds Spotted in Nordic Skies'],
    ['title' => 'Desert Expedition Reveals Hidden Oasis Ecosystem'],
    ['title' => 'Mountain Observatory Captures Meteor Shower Images']
];

$news = SmartArray::new($articles)->asHtml();

// Create a news listing with featured articles
echo "<div class='news-list'>\n";
foreach ($news as $article) {
    // First 3 articles get heading treatment
    if ($article->position() <= 3) {
        echo "<h1>$article->title</h1>\n";
    } else {
        // Remaining articles as regular text
        echo "$article->title<br>\n";
    }
}
echo "</div>\n";

$topSellers = [
    ['rank' => 1, 'title' => 'The Great Gatsby', 'sales' => 25000000],
    ['rank' => 2, 'title' => '1984', 'sales' => 20000000],
    ['rank' => 3, 'title' => 'To Kill a Mockingbird', 'sales' => 18000000],
    ['rank' => 4, 'title' => 'The Catcher in the Rye', 'sales' => 15000000],
    ['rank' => 5, 'title' => 'The Hobbit', 'sales' => 14000000]
];

$books = SmartArray::new($topSellers)->asHtml();

// Get specific positions (0-based indexing)
echo $books->nth(0)->title;  // "The Great Gatsby" (first book)
echo $books->nth(2)->title;  // "To Kill a Mockingbird" (third book)

// Use negative indices to count from the end
echo $books->nth(-1)->title; // "The Hobbit" (last book)
echo $books->nth(-2)->title; // "The Catcher in the Rye" (second-to-last)

// Common use cases:

// Get podium finishers in a competition
$goldMedalist   = $results->nth(0);
$silverMedalist = $results->nth(1);
$bronzeMedalist = $results->nth(2);

// Display recent activity with the newest first
$mostRecent       = $activities->nth(0);
$secondMostRecent = $activities->nth(1);

// Show last few items in a feed
$latestLogEntry    = $log->nth(-1);
$secondLatestEntry = $log->nth(-2);

$authors = [
    ['author_id' => 101, 'name' => 'Jane Austen',    'genre' => 'Literary Fiction'],
    ['author_id' => 102, 'name' => 'George Orwell',  'genre' => 'Political Fiction'],
    ['author_id' => 103, 'name' => 'Isaac Asimov',   'genre' => 'Science Fiction'],
    ['author_id' => 104, 'name' => 'Agatha Christie','genre' => 'Mystery'],
];

// Create a lookup array indexed by author_id
$authorById = SmartArray::new($authors)->indexBy('author_id')->asHtml();

// Now you can quickly look up authors by their ID
echo $authorById->get(101)->name;  // Output: Jane Austen
echo $authorById->get(103)->genre; // Output: Science Fiction

// Particularly useful when joining data from multiple sources
$articles = [
    ['article_id' => 1, 'title' => 'Pride and Programming', 'author_id' => 101],
    ['article_id' => 2, 'title' => 'Digital Dystopia',      'author_id' => 102],
    ['article_id' => 3, 'title' => 'Robot Psychology',      'author_id' => 103],
];

// Display articles with author information
foreach (SmartArray::new($articles)->asHtml() as $article) {
    $author = $authorById->get($article->author_id);
    echo "Title: $article->title\n";
    echo "By: $author->name ($author->genre)\n\n";
}

$books = [
    ['title' => 'Pride and Prejudice', 'author' => 'Jane Austen',   'genre' => 'Literary Fiction', 'year' => 1813],
    ['title' => '1984',                'author' => 'George Orwell', 'genre' => 'Science Fiction',  'year' => 1949],
    ['title' => 'Foundation',          'author' => 'Isaac Asimov',  'genre' => 'Science Fiction',  'year' => 1951],
    ['title' => 'Emma',                'author' => 'Jane Austen',   'genre' => 'Literary Fiction', 'year' => 1815],
    ['title' => 'I, Robot',            'author' => 'Isaac Asimov',  'genre' => 'Science Fiction',  'year' => 1950],
    ['title' => 'Persuasion',          'author' => 'Jane Austen',   'genre' => 'Literary Fiction', 'year' => 1818],
];

// Group books by genre
$booksByGenre = SmartArray::new($books)->groupBy('genre')->asHtml();

// Now you can work with each genre's books separately
foreach ($booksByGenre as $genre => $relatedBooks) {
    echo "\n$genre Books:\n";
    echo str_repeat('-', strlen($genre) + 7) . "\n";

    foreach ($relatedBooks as $book) {
        echo "- $book->title ($book->year)\n";
    }
}

// Group by author to analyze their work
$booksByAuthor = SmartArray::new($books)->groupBy('author')->asHtml();

foreach ($booksByAuthor as $author => $authorBooks) {
    $years = $authorBooks->pluck('year')->values()->sort();
    echo "\n$author published {$authorBooks->count()} books ({$years->first()}-{$years->last()}):\n";

    foreach ($authorBooks->sortBy('year') as $book) {
        echo "- $book->title ($book->year)\n";
    }
}

$articles = [
    ['title' => 'Getting Started with PHP',  'tag' => 'PHP'],
    ['title' => 'Understanding Unit Tests',   'tag' => 'Testing'],
    ['title' => 'Data Handling Techniques',   'tag' => 'PHP'],
    ['title' => 'MySQL Best Practices',       'tag' => 'Databases'],
    ['title' => 'Advanced PHP Techniques',    'tag' => 'PHP'],
];

// Extract unique, sorted tags as a comma-separated display string
$tagList = SmartArray::new($articles)->pluck('tag')->unique()->sort()->implode(', ');

// Or for better readability, the same operation can be split across multiple lines:
$tagList = SmartArray::new($articles)
                ->pluck('tag')               // Extract tag field: ["PHP", "Testing", "PHP", "Databases", "PHP"]
                ->unique()                   // Remove duplicates: ["PHP", "Testing", "Databases"]
                ->sort()                     // Sort alphabetically: ["Databases", "PHP", "Testing"]
                ->implode(', ');             // Join as string: "Databases, PHP, Testing"

echo "Topics: $tagList"; // Output: "Topics: Databases, PHP, Testing"

$rows = SmartArray::new([
    ['name' => "John O'Connor",  'city' => 'New York',    'status' => 'Active'],
    ['name' => 'Jane <script>',  'city' => 'Los Angeles', 'status' => 'Pending'],
    ['name' => 'Tom & Jerry',    'city' => 'Vancouver',   'status' => 'Active'],
])->asHtml();

$countries = SmartArray::new(['us' => 'United States', 'ca' => 'Canada', 'mx' => 'Mexico'])->asHtml();

$records = [
    ['id' => 10, 'name' => "John O'Connor",  'city' => 'New York'],
    ['id' => 15, 'name' => 'Xena "X" Smith', 'city' => 'Los Angeles'],
    ['id' => 20, 'name' => 'Tom & Jerry',    'city' => 'Vancouver'],
];
$users = SmartArray::new($records)->asHtml();

foreach ($users as $user) {
    if ($user->isFirst()) { echo "<table border='1' cellpadding='10' style='text-align: center'>\n<tr>\n"; }
    echo "<td><h1>$user->name</h1>$user->city</td>\n"; // values are automatically HTML-encoded by SmartString
    if ($user->isLast())  { echo "</tr>\n</table>\n"; }
}

$users = SmartArrayHtml::new([
    ['id' => 10, 'name' => "John O'Connor",  'city' => 'New York'],
    ['id' => 20, 'name' => 'Tom & Jerry',    'city' => 'Vancouver'],
]);
print_r($users);

$users->help();  // Displays comprehensive documentation and examples