Data Manipulation Techniques in PHP

Introduction to Data Manipulation

Welcome to our lesson on practical data manipulation techniques using PHP! In this lesson, we will explore how to manipulate data structures with PHP's arrays and associative arrays. Our operations will be conveniently bundled within a PHP class, offering clean and organized code. Let's get our tools ready and dive into data manipulation in PHP.

Here's a simple PHP class, DataStream, that will be our toolbox for handling data:

PHP
<?php

class DataStream {
    private $data;

    public function __construct(array $data) {
        $this->data = $data;
    }
}

?>

Data Projection in Practice

Our first stop is data projection, where we focus on extracting specific details from our dataset. Suppose we have data about people and we are interested in only names and ages. We will extend our DataStream class with a project method that uses PHP's array_map to accomplish this task:

<?php

class DataStream {
    private $data;

    public function __construct(array $data) {
        $this->data = $data;
    }

    public function project(callable $projectFunc): DataStream {
        $projectedData = array_map($projectFunc, $this->data);
        return new DataStream($projectedData);
    }

    public function printData(): void {
        foreach ($this->data as $entry) {
            echo join(', ', array_map(
                fn($value, $key) => "$key: $value",
                $entry,
                array_keys($entry)
            )) . "\n";
        }
    }
}

$data = [
    ['name' => 'Alice', 'age' => '25', 'profession' => 'Engineer'],
    ['name' => 'Bob', 'age' => '30', 'profession' => 'Doctor']
];

$ds = new DataStream($data);

$projectedDs = $ds->project(function($entry) {
    return ['name' => $entry['name'], 'age' => $entry['age']];
});

$projectedDs->printData();
// Outputs:
// name: Alice, age: 25
// name: Bob, age: 30

?>

Data Filtering in Practice

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal