DEV Community

Cover image for Mastering PHP Arrays
Eric The Coder
Eric The Coder

Posted on • Edited on

10 2

Mastering PHP Arrays

If you like this post and want more follow me on Twitter: Follow @justericchapman

PHP Arrays

//Array declaration
$names = ['Mike', 'Peter', 'Shawn', 'John'];

//add to array
$names[] = 'Micheal';

// Array merge
$array3 = array_merge($array1, $array2);

// Array Concat with Spread Operator
$names = ['Mike', 'Peter', 'Paul'];
$people = ['John', ...$names]; // ['John', 'Mike', 'Peter', 'Paul']

//Array to string
$text = implode(', ', $names); // 'Mike, Peter, Paul'

// String to Array
echo explode(',', $text); // ['Mike', 'Peter', 'Paul']

// Direct access
echo $names[1]; //output Peter

// Remove and preserve keys
unset($names[1]); 
// It is now => [0 => 'Mike', 2 => 'Paul']

// Or remove and change keys
array_splice($names, 1, 1);
// It is now => [0 => 'Mike', 1 => 'Paul']

//loop for each array entry
foreach($names as $name) { 
   echo 'Hello ' . $name;
}

// Number of items in a Array
echo count($names);  

//Associative array:
$person = ['age' => 45, 'genre' => 'men'];

//Add to ass. array:
$person['name'] = 'Mike';

//loop ass. array key => value: 
foreach($names as $key => $value) { 
   echo $key . ' : ' . $value;
}

// Check if a specific key exist
echo array_key_exists('age', $person);

// Return keys
echo array_keys($person); // ['age', 'genre']

// Return values
echo array_values($person); // [45, 'men']

//Array filter (return a filtered array)
$filteredPeople = array_filter($people, function ($person) {
    return $person->active;
});

// Array map (return transform array):
$onlyNames = array_map(function($person) {
    return ['name' => $person->name];
}, $people);

# Search associative array
$items = [
        ['id' => '100', 'name' => 'product 1'],
        ['id' => '200', 'name' => 'product 2'],
        ['id' => '300', 'name' => 'product 3'],
        ['id' => '400', 'name' => 'product 4'],
    ];

# search all value in the 'name' column
$found_key = array_search('product 3', array_column($items, 'name'));
# return 2

Enter fullscreen mode Exit fullscreen mode

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (5)

Collapse
 
goodevilgenius profile image
Dan Jones
$names = ['Mike', 'Peter', 'Paul'];

//Remove array entry:
unset($names['Peter']);
Enter fullscreen mode Exit fullscreen mode

That unset will not do what you want it to do. You need one of the following:

// To preserve keys
unset($names[1]); 
// It is now => [0 => 'Mike', 2 => 'Paul']

// or to change keys
array_splice($name, 1, 1);
// It is now => [0 => 'Mike', 1 => 'Paul']
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ericchapman profile image
Eric The Coder

Did not know that one... Thanks for the tips!

Collapse
 
goodevilgenius profile image
Dan Jones
//Array filter (return a filtered array)
$filteredPeople = array_filter($people, function ($person) {
    return $names->active;
});
Enter fullscreen mode Exit fullscreen mode

This also won't work. I think maybe you meant:

//Array filter (return a filtered array)
$filteredPeople = array_filter($people, function ($person) {
    return $person->active;
});
Enter fullscreen mode Exit fullscreen mode

Although, I have no idea what $person is supposed to be, since it's not clear from your examples.

Collapse
 
ericchapman profile image
Eric The Coder

Oupss. Typo $names should be $person

$person is the singular noun of the plural $people

Collapse
 
suckup_de profile image
Lars Moelleken

Hi, here I created a wrapper around php array functions, so that you can use it in a more OOP way. github.com/voku/Arrayy

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay