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
Top comments (5)
That
unset
will not do what you want it to do. You need one of the following:Did not know that one... Thanks for the tips!
This also won't work. I think maybe you meant:
Although, I have no idea what
$person
is supposed to be, since it's not clear from your examples.Oupss. Typo $names should be $person
$person is the singular noun of the plural $people
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