Search notes:

PHP code snippets: arrays

array(…) (like list()) is not a function but rather a language construct.

Add elements to an array

The following example uses two alternatives to add an element to an array.
The foreach loop prints five elements: one, two, three, four, five.
<html><head><title>Add elements to an array</title></head>
<body>

  <?php 
   
 //
 // Create an array with three elements:
 //
    $a = array('one', 'two', 'three');
    
 //
 // Append 'four' to the array:
 //
    $a[] = 'four';                     // Append 'four' to the array:

 //
 // same thing, but with array_push
 //
    array_push($a, 'five');

 //
 // Print elements
 //
    foreach ($a as $val) {
       print("<br>$val");
    }

  ?>

</body>
</html>
Github repository about-php, path: /array/add-elements.html
See also array_push()

join

join($sep, $ary) creates a string from the array $ary by joining the array's elements by the value of $sep.
join is an alias for implode.
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>join</title>
</head>
<body>

  <?php

    $a = array("foo", "bar", "baz");

    print join (" - ", $a);

  ?>

</body>
</html>
Github repository about-php, path: /array/join.html
join (or the equivalent implode) might be used to cheaply print arrays (for example in case of the error Notice: Array to string conversion).

Number of elements in an array

The number of elements in an array is returned by the function count($ary) that takes an array (or an object that implements the Countable interface).
<?php

header('Content-Type: text/plain');

$ary = array('foo', 'bar', 'baz');
printf('$ary has %d elements', count($ary));

?>
Github repository about-php, path: /array/count.php
Other programming languages sometimes have a member method length or something similar to return this number.

array_map

array_map(function($i) { … }, $ary);
array_map('func_name'       , $ary);

Using a lambda-function

<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>array_map</title>
</head>
<body>

<?php

  $numbers = array(1,4,6,2,1,3);
  $squared = array_map(function($n) { return $n * $n; }, $numbers);

  print('Squared: <ul>');
  foreach ($squared as $s) {
     print("<li>$s");
  }
  print("</ul>");

?>

</body>
</html>
Github repository about-php, path: /array/map-func.html

Using a user defined function

<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>array_map</title>
</head>
<body>

<?php

  function square($s) {
     return $s * $s;
  }

  $numbers = array(1,4,6,2,1,3);
  $squared = array_map('square', $numbers);

  print('Squared: <ul>');
  foreach ($squared as $s) {
     print("<li>$s");
  }
  print("</ul>");

?>

</body>
</html>
Github repository about-php, path: /array/map-name.html
`

Short syntax

<?

$array = ['one', 'two', 'three'];

$dict  = [ 'txt' => 'hello world',
           'num' => 42 ];

print("<pre><code>");
print("array[ 1   ] = " . $array[ 1   ] . "<br>");
print("dict ['num'] = " . $dict ['num'] . "<br>");
print("</code></pre>");

?>
Github repository about-php, path: /array/short-syntax.php
And another example
<?php

$dict = [];


$dict += [ 'numbers'         => [1, 2, 3],
           'numbers-spelled' => ['one', 'two', 'XXX', 'three']
         ];


$dict['numbers'        ][] = 4;
$dict['numbers-spelled'][] ='four';

$dict['words'][] = 'foo';
$dict['words'][] = 'bar';
$dict['words'][] = 'xxx';
$dict['words'][] = 'baz';


#
#  Remove an element from the dictionary
#
unset($dict['words'][2]);
unset($dict['numbers-spelled'][2]);

foreach ($dict as $k => $v) {
   print("$k: " . join(', ', $v) . "\n");
}

?>
Github repository about-php, path: /array/add-remove.php

See also

Associative arrays
array_is_list($ary) returns true if $ary is a sequential array and false if is an associative array.
Other PHP snippets

Index