๐ŸŽ“ A1Learner
๐Ÿ”

PHP Array Functions

Array functions are built-in tools that work on whole arrays. Some of them change the array, and some only read from it.

Counting before and after a growth

The list starts with two items and its count prints. One more item is appended, and the count prints again.

<?php
$list = ["milk", "bread"];
echo count($list) . "\n";
$list[] = "eggs";
echo count($list) . "\n";

Appending with empty brackets

Empty brackets add a value at the end of the array. print_r shows eggs in the last place.

<?php
$list = ["milk", "bread"];
$list[] = "eggs";
print_r($list);

Adding two values with array_push

array_push adds both new values at the end. The count it hands back prints first, and print_r shows the grown list.

<?php
$list = ["milk", "bread"];
$count = array_push($list, "eggs", "rice");
echo $count . "\n";
print_r($list);

Testing for a value with in_array

in_array answers true when the value sits in the array. var_dump shows true for milk and false for cheese.

<?php
$list = ["milk", "bread", "eggs"];
var_dump(in_array("milk", $list));
var_dump(in_array("cheese", $list));

Joining two arrays with array_merge

array_merge places the values of the second array after the first ones. print_r shows one joined array.

<?php
$first = ["milk", "bread"];
$second = ["eggs", "rice"];
$all = array_merge($first, $second);
print_r($all);

Example

<?php
$guests = ["Ana", "Bo"];
$guests[] = "Cy";
array_push($guests, "Dee", "Eli");
print_r($guests);
echo count($guests) . " guests\n";

Key points

  • Built-in array functions do common jobs on whole arrays at once.
  • An empty pair of brackets after a name appends a value to that array.
  • array_push adds one or more values at the end of an array.
  • array_push hands back the new count of the array.
  • in_array tests whether a value sits in an array.
  • array_merge joins two arrays into one new array.

In this example, the guest list starts with two names. Empty brackets add Cy, and array_push adds Dee and Eli. print_r shows all five names in order, and the last line prints the final count.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

What does var_dump(in_array("rice", $list)) print when rice is not in $list?