DEV Community

Carlos Viana
Carlos Viana

Posted on • Edited on

7 1 1 1 1

Manipulating arrays in PHP: The Essential Guide!

An array is a data structure that stores a collection of elements, usually of the same type, in a single variable. These elements can be numbers, strings, objects, or even other arrays. Arrays allow you to store and access multiple values ​​in an ordered manner, using indexes.

Creating an Array:
You can create arrays using the array() function or the short array syntax [].

<?php

// Using array() function
$fruits1 = array("Apple", "Banana", "Orange");

var_dump($fruits1);

// Using short array syntax
$fruits2 = ["Apple", "Banana", "Orange"];

var_dump($fruits2);
Enter fullscreen mode Exit fullscreen mode

Accessing Array Elements:
You can access array elements by referring to their index.

<?php

$fruits = ["Apple", "Banana", "Orange"];

echo $fruits[0]; // Outputs: Apple

Enter fullscreen mode Exit fullscreen mode

Adding Elements to an Array: Use array_push() or simply assign a value to a new index to add elements to an array.

<?php

$fruits = ["Apple", "Banana", "Orange"];

// Adding using array_push()
array_push($fruits, "Grapes");

// Adding using array index
$fruits[] = "Mango";

var_dump($fruits);
Enter fullscreen mode Exit fullscreen mode

Removing Elements from an Array: You can remove elements from an array using unset() or array functions like array_pop() and array_shift().

<?php 

$fruits = ["Apple", "Banana", "Orange"];

// Remove last element
array_pop($fruits);

// Remove first element
array_shift($fruits);

// Remove element by index
unset($fruits[1]); // Removes Banana

var_dump($fruits);
Enter fullscreen mode Exit fullscreen mode

Iterating Over an Array: Loop through an array using foreach().

<?php

$fruits = ["Apple", "Banana", "Orange"];

foreach ($fruits as $fruit) {
    echo $fruit;
}
Enter fullscreen mode Exit fullscreen mode

Merging Arrays: Combine arrays using array_merge().

<?php 

$fruits = ["Apple", "Banana", "Orange"];

$moreFruits = ["Pineapple", "Watermelon"];

$allFruits = array_merge($fruits, $moreFruits);

var_dump($allFruits);
Enter fullscreen mode Exit fullscreen mode

Sorting Arrays: You can sort arrays with functions like sort(), rsort(), asort(), ksort(), etc.

<?php 

$fruits = ["Apple", "Banana", "Orange"];

sort($fruits); // Sort in ascending order

var_dump($fruits);
Enter fullscreen mode Exit fullscreen mode

You can run the code at https://onecompiler.com/php

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Retry later
👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay