You are on page 1of 10

Multidimensional arrays in PHP

An array that contains one or more arrays is Multidimensional arrays. A multi-dimensional array
of each element in the main array can also be an array. And each element in the sub-array can
be an array, and so on. Values in the multi-dimensional array are accessed using multiple
indexes.

Example
To implement multidimensional arrays in PHP, the code is as follows−
 Live Demo

<?php
$marks = array(
    "kevin" => array (
      "physics" => 95,
      "maths" => 90,
    ),
    "ryan" => array (
      "physics" => 92,
      "maths" => 97,
    ),
);
   echo "Marks for kevin in physics : " ;
   echo $marks['kevin']['physics'] . "
";
   echo "Marks for ryan in maths : ";
   echo $marks['ryan']['maths'] . "
";
?>

Output
This will produce the following output−
Marks for kevin in physics : 95
Marks for ryan in maths : 97
Access the Elements of a Multi-Dimensional
Array
To access an element of a multi-dimensional array, specify an index number in each of
the array's dimensions.

This statement accesses the value of the element in the first row (0) and third
column (2) of the letters array.

Example
string letters[2][4] = {
  { "A", "B", "C", "D" },
  { "E", "F", "G", "H" }
};

cout << letters[0][2];  // Outputs "C"

Change Elements in a Multi-Dimensional Array


To change the value of an element, refer to the index number of the element in each of
the dimensions:

Example
string letters[2][4] = {
  { "A", "B", "C", "D" },
  { "E", "F", "G", "H" }
};
letters[0][0] = "Z";

cout << letters[0][0];  // Now outputs "Z" instead of "A"

Loop Through a Multi-Dimensional


Array
To loop through a multi-dimensional array, you need one loop for each of
the array's dimensions.
The following example outputs all elements in the letters array:

Example
string letters[2][4] = {
  { "A", "B", "C", "D" },
  { "E", "F", "G", "H" }
};

for (int i = 0; i < 2; i++) {


  for (int j = 0; j < 4; j++) {
    cout << letters[i][j] << "\n";
  }
}

This example shows how to loop through a three-dimensional array:

Example
string letters[2][2][2] = {
  {
    { "A", "B" },
    { "C", "D" }
  },
  {
    { "E", "F" },
    { "G", "H" }
  }
};

for (int i = 0; i < 2; i++) {


  for (int j = 0; j < 2; j++) {
    for (int k = 0; k < 2; k++) {
      cout << letters[i][j][k] << "\n";
    }
  }
}
How to loop through a multidimensional array in PHP?
Arrays are iterable data structures meaning that an iterator or a loop can access
its elements. Loops are central to any programming language, and PHP also has
several different loops. The foreach loop is quite famous for associative arrays in
PHP.

The foreach references keys and values as it loops through an associative array. It
also relieves a programmer of the possibility of running over the array out-of-
bounds error, thrown when an index exceeds the array’s limit.
Besides foreach, PHP has for, while, and do-while loops. This article answers how
to loop through a multidimensional array in PHP, and thus it will focus on the
foreach loop. Nevertheless, you can read an in-depth article about the loops in
PHP. 

Creating and Accessing Strings:

What is String in PHP?

A string is a sequence of letters, numbers, special characters and arithmetic values or


combination of all. The simplest way to create a string is to enclose the string literal (i.e. string
characters) in single quotation marks (‘), like this:

Example: $my_string = ‘Hello World’;


The escape-sequence replacements are:

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
Calculating the Length of a String

The strlen() function is used to calculate the number of characters inside a string. It also

includes the blank spaces inside the string.


Example:
<!DOCTYPE html>

<html lang="en">

<head>

<title>PHP Calculate String Length</title>

</head>

<body>
<?php

$my_str = 'Welcome to Devops School';

// Calculating and displaying string length

echo strlen($my_str);

?>

</body>

</html>

Counting Number of Words in a String

The str_word_count() function counts the number of words in a string.


Example:
<!DOCTYPE html>

<html lang="en">

<head>

<title>PHP Find the Number of Words in a String </title>

</head>

<body>

<?php

$my_str = 'The quick brown fox jumps over the lazy dog.';

// Calculating and displaying number of words

echo str_word_count($my_str);

?>

</body>
</html>

Replacing Text within Strings

The str_replace() replaces all occurrences of the search text within the


target string.
Example:
<!DOCTYPE html>

<html lang="en">

<head>

<title>PHP Replacing Text within a String </title>

</head>

<body>

<?php

$my_str = 'If the facts do not fit the theory, change the facts.';

// Display replaced string

echo str_replace("facts", "truth", $my_str);

?>

</body>

</html>

Reversing a String
The strrev() function reverses a string.

Example:
<!DOCTYPE html>

<html lang="en">
<head>

<title>PHP Reversing a String</title>

</head>

<body>

<?php

$my_str = 'You can do anything, but not everything.';

// Display reversed string

echo strrev($my_str);

?>

</body>

</html>

Strpos() – Search For a Text Within a String


The PHP strpos() the function searches for a specific text within a string. If a match is found,

the function returns the character position of the first match. If no match is found, it will return
FALSE.
Example:
<!DOCTYPE html>

<html>

<body>

<?php

echo strpos("Hello world!", "world");

?>

</body>

</html>

Replacing Text Within Strings and Formatting Strings:


PHP gives you a couple of useful functions for replacing text in a string:

 str_replace() searches for one string of text and replaces it with another.

 substr_replace() replaces text at a specified position within a string

Searching and replacing with str_replace()

str_replace() works much like the “replace all” function of a word processor, replacing all
occurrences of a chunk of text with a different chunk of text. It takes 3 arguments:

 The text to search for

 The text to replace it with

 The string to search through

str_replace() returns the string with all occurrences of the search text replaced with the
replacement text. (The original string is untouched.) For example:

$myString = "'My amiable lady!' he interrupted, with an almost diabolical sneer on his face.
'Where is she--my amiable lady?'";

echo str_replace( 'lady', 'wife', $myString );

The above code displays:

'My amiable wife!' he interrupted, with an almost diabolical sneer on

Replacing part of a string with substr_replace()

substr_replace() replaces text at a specified index position in a string. To use it, pass the
following arguments:
 The string to work on

 The replacement text

 The index position at which to start the replacement

By default, substr_replace() replaces everything from the start position to the end of the string
with the supplied replacement text. For example:

$myString = "Nothing was stirring except a brindled, grey cat";

echo substr_replace( $myString, "moving", 12 ); // Displays "Nothing w

You might also like