PHP PHP Array Functions - Examples and Usage

Learn how to manipulate arrays in PHP with these useful array functions. From adding and removing elements to sorting and converting arrays, this guide covers it all.

$fruits = [];
$fruits = ['apples', 'avocados', 'oranges', 'bananas'];
$veggies = ['broccoli' => 1, 'lettuce' => 5, 'celery' => 0, 'spinach' => 5];
$food = [$fruits, $veggies];
$multi = [['foo' => 'bar'], ['x' => 'y'], 'key' => 'value', 3, 2, 1];

$a = [];
is_array($a);
is_array("string");
empty($a);
count($a);
sizeof($a);
$numbers = [1, 2, 3];
in_array(1, $numbers);
in_array(99, $numbers);
$mix = [1, true, 'hello'];
var_dump($mix);
print_r($mix);

$fruits[0];
$veggies['lettuce'];

list($first_item, $second_item) = $fruits;

$vars = ['a' => 123];
extract($vars);
echo $a;

$fruits[] = 'apples';
$veggies['potato'] = 3;

array_unshift($fruits, "raspberries", "blueberries");
array_push($fruits, "raspberries", "blueberries");

$x = 1;
$y = 2;
$z = 3;
$vars = compact("x", array("y", "z"), "random");
print_r($vars);

$colors = ['green', 'red', 'yellow'];
$food = ['avocado', 'apple', 'banana'];
$colored_food = array_combine($colors, $food);
$result = array_merge($fruits, $veggies);
$base = ["orange", "banana", "apple", "raspberry"];
$replacements = [0 => "pineapple", 4 => "cherry"];
$replacements2 = [0 => "grape"];
$basket = array_replace($base, $replacements, $replacements2);

$fruit = array_shift($fruits);
$fruit = array_pop($fruits);
unset($fruits['apples']);

$a = [1, 2, 3, NULL, "", "text", 4, 5];
$a = array_filter($a);
$a = array_filter($a, 'is_numeric');

$from = ["a" => "green", "red", "blue"];
$against = ["b" => "green", "yellow", "red"];
$result = array_diff($from, $against);
print_r($result);

$from = ["a" => "green", "red", "blue"];
$against = ["b" => "green", "yellow", "red"];
$result = array_intersect($from, $against);
print_r($result);

foreach ($fruits as $fruit) {
    echo "fruit: $fruit \n";
}

foreach ($fruits as $inx => $fruit) {
    echo "$inx. fruit: $fruit \n";
}

$max = count($fruits);
for ($i = 0; $i < $max; $i++) {
    if ($i === 0) {
        continue;
    }
    echo $fruits[$i];
    if ($i === 3) {
        break;
    }
}

$i = 10;
do {
    echo $i;
} while ($i--);

$fruits_str = implode(',', $fruits);
$fruits = explode(',', $fruits_str);
$json = json_encode([1, "hello", 'foo' => 'bar']);
echo $json;
$array = json_decode($json, true);
var_dump($array);

$numbers = range(1, 10);
shuffle($numbers);
echo implode(",", $numbers);
arsort($numbers);
echo implode(",", $numbers);
asort($numbers);
echo implode(",", $numbers);