PHP Arrays and Strings Fundamentals

Introduction

Welcome!

Before diving into PHP essentials for your development toolkit, let's start with some foundational PHP features — namely, arrays and strings. These features allow PHP to group multiple elements, such as numbers or characters, under a single entity.

Understanding Arrays and Strings

As our starting point, it's crucial to understand how arrays and strings function in PHP. Arrays in PHP are flexible and can hold different types of data, while strings are sequences of characters that can be effectively manipulated using a variety of helpful functions. Let's see examples:

PHP
<?php

// Defining an array and a string
$myArray = [1, 2, 3, 4];
$myString = "hello";

// Now let's try to change the first element of both these features
// Changing the first element of the array
$myArray[0] = 100;

// For strings, we can use string replacement functions to obtain a new string
$newString = str_replace('h', 'H', $myString);

echo implode(", ", $myArray) . "\n"; // prints 100, 2, 3, 4
echo $myString . "\n"; // prints hello
echo $newString . "\n"; // prints Hello
?>

Diving Into Lists

Imagine having to take an inventory of all flora in a forest without a list at your disposal — seems near impossible, right? That's precisely the purpose arrays serve in PHP. They let us organize data so that each item holds a definite position or an index. The index allows us to access or modify each item individually.

Working with arrays in PHP is as simple as this:

PHP
<?php

// Creating an array
$fruits = ["apple", "banana", "cherry"];

// Add a new element at the end
$fruits[] = "date"; // ['apple', 'banana', 'cherry', 'date']
echo implode(", ", $fruits) . "\n"; // prints apple, banana, cherry, date

// Inserting an element at a specific position
array_splice($fruits, 1, 0, "bilberry"); // ['apple', 'bilberry', 'banana', 'cherry', 'date']
echo implode(", ", $fruits) . "\n"; // prints apple, bilberry, banana, cherry, date

// Removing a particular element
unset($fruits[array_search("banana", $fruits)]); // ['apple', 'bilberry', 'cherry', 'date']
echo implode(", ", $fruits) . "\n"; // prints apple, bilberry, cherry, date

// Accessing elements using indexing
$firstFruit = $fruits[0]; // apple
echo $firstFruit . "\n"; // prints apple

$lastFruit = end($fruits); // date
echo $lastFruit . "\n"; // prints date

// Converting static array to a dynamic list and vice versa
$fruitArray = ["kiwi", "lemon", "mango"];
$fruitList = array_merge($fruits, $fruitArray);
echo implode(", ", $fruitList) . "\n"; // prints apple, bilberry, cherry, date, kiwi, lemon, mango

$newFruitArray = array_values($fruitArray);
echo implode(", ", $newFruitArray) . "\n"; // prints kiwi, lemon, mango
?>
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