PHP Indexed Array

PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0.

PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.

Definition

There are two ways to define indexed array:

1st way:

  1. $size=array(“Big”,”Medium”,”Short”);  

2nd way:

$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  

PHP Indexed Array Example

 

<?php  
$size=array("Big","Medium","Short");  
echo "Size: $size[0], $size[1] and $size[2]";  
?> 

Output:Size: Big, Medium and Short

<?php  
$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  
echo "Size: $size[0], $size[1] and $size[2]";  
?>  

Output:Size: Big, Medium and Short

Traversing PHP Indexed Array

We can easily traverse array in PHP using foreach loop. Let’s see a simple example to traverse all the elements of PHP array.

<?php  
$size=array("Big","Medium","Short");  
foreach( $size as $s )  
{  
  echo "Size is: $s<br />";  
}  
?>  

Output:

Size is: Big
Size is: Medium
Size is: Short

Count Length of PHP Indexed Array

PHP provides count() function which returns length of an array.

<?php  
$size=array("Big","Medium","Short");  
echo count($size);  
?>  

Output:

3

JavaScript Array

JavaScript Array is also like a data type that is used to store one or more than one value of a similar type together. It’s like a container which is used to store values in a single variable. We can use an array to store values of string type, or integer type, or an object or any other valid data type in JavaScript. But the type of all the values stored in an array should be the same.

An array in JavaScript is “not” provided contiguous memory locations to store its values. In JavaScript, we do not have to provide the length of the array while declaring an array, yes, we can simply declare an empty array and then add as many elements in it as we want. Arrays are list-like objects which have many built-in functions defined in its prototype for accessing elements, adding elements, array traversal, etc.

JavaScript does not have a specific array datatype for defining arrays. But, there is a predefined Array object and its methods to work with arrays. Arrays also have properties in JavaScript like length which is not a function but a property.

We can create JavaScript array either by using the new keyword or using the array literal notation i.e. [](square brackets).

JavaScript Array using Literal Notation

We can also create an array using array literal notation. An Array literal notation is a comma-separated list of items enclosed within square brackets.

Syntax to create an Array using Array Literal notation:

Creating an array using the array literal notation is simple than creating array using new keyword.

var arr = [ ];  // empty array

var fruits = ["mango","apple","orange","guava"];  // Array having elements

Let’s take an example to see how we can create a simple array using array literal notation.

<script>
    var arr = ["Yamaha","Honda","KTM"];
    console.log(arr.length)
</script>

3

As you can see in the above code example, we have used the length property of array to print the count of elements present in it. The length property of array is used very frequently while traversing an array.

JavaScript Array using new

  • We create an empty Array whenever we don’t know the exact number of elements to be inserted in the Array.
  • An empty array can be created using the new keyword.
  • We can then use the push() method to add elements at the end of the array, or use the unshift() method to add to the front of the array. There are many different ways of adding data to an array in JavaScript.

Syntax to create an Array:

Following is the syntax for creating an array using the new keyword.

let arr = new Array(); // empty array

let arr = new Array(10); // array of 10 elements size

let arr = new Array("Java","C","C++"); // array with 3 values

Now, let’s take a simple example to see this in action.

<script>
    let fruits = new Array("mango","apple","banana","guava");
    console.log(fruits);
</script>

[“mango”, “apple”, “banana”, “guava”]

JavaScript Array: Accessing Elements

We can access array elements by using index value of the stored data elements. Ever data element stored in an array is stored at an index. The array index starts from 0 and goes upto the value (Array.length – 1). So, the first element will be stored at index value 0 and the last element is stored at index value (Array.length – 1)

let fruits = ["mango","apple","orange","guava"];   // Array having elements

console.log(fruits[0]);   // Accessing element
console.log(fruits[1]);   // Accessing element
console.log(fruits[fruits.length-1]);   // Accessing element

mango apple guava

JavaScript Array: Traversal or Iteration

Since an array is an object, we can iterate over its elements using for loop. We have already covered JavaScript for Loop in one of our previous tutorials. We have used the for-of loop in the below example, but you can use the simple for loop as well.

let fruits = ["mango", "apple", "orange", "guava"];  // Array having elements
for(f of fruits)    // Traversing array 
	document.wrtie(f + " ");

mango apple orange guava

For the beginners, let’s see one example of array traversal using the basic for loop as well,

let fruits = ["mango", "apple", "orange", "guava"];  // Array having elements
// Traversing array 
for(let i=0; i < fruits.length; i++)    
{
	document.write(fruits[i] + " ");
}

Array forEach Function:

To loop over an array, we can also use the Array function forEach which is defined in its prototype definition. Let’s see an example for that,

let bikes = ["Honda", "KTM", "Yamaha"];
// using forEach function
bikes.forEach(function(item, index, array) {
    document.write(item, index);
})

Honda 0 KTM 1 Yamaha 2

JavaScript Array Object Methods

Below we have specified some of the popular methods that are used for performing various operations on array in JavaScript like adding a new element, removing an element, searching an index of an element, etc.

1. concat(): Joins two or more arrays and returns the joined array.

2. join(): Join all the elements of an array into a string.

3. pop(): Removes the last element of an array and returns that element.

4. reverse(): Reverse the order of a list of elements in an array.

5. shift(): Removes the first element of an array and returns that element.

6. slice(): Selects a part of an array and return that part as a new array.

7. sort(): Sort the elements of an array.

8. push(): Adds new element as the last element and returns the length of the new array.

9. unshift(): Adds new elements to the array and returns the new length.

10. splice(): Adds or removes elements of an array.

11. fill(): Fill the elements into an array with static values.

12. every(): It determines whether all elements of an array are satisfying the provided function conditions.

13. isArray(): To check if the value is an array or not.

14. indexOf(): To find the index of an element in the array.

15. forEach(): To loop over the array values.

Apart from these, there are many more Array prototype functions available. Let’s see a few of these functions in action:

1. Add an element as the Last Element of Array

let bikes = ["Honda", "KTM", "Yamaha"];
bikes.push("Triumph");
console.log(bikes);

[“Honda”, “KTM”, “Yamaha”,”Triumph”]

2. Add an element as the First Element of Array

let bikes = ["Honda", "KTM", "Yamaha"];
bikes.unshift("Triumph");
console.log(bikes);

[“Triumph”,”Honda”, “KTM”, “Yamaha”]

3. Find the index of an Array Element

let bikes = ["Honda", "KTM", "Yamaha"];
// use console.log or document.write for output
console.log(bikes.indexOf("KTM");

1

4. Reverse the Array

let bikes = ["Honda", "KTM", "Yamaha"];
console.log(bikes.reverse());

[“Yamaha”,”KTM”,”Honda”]

Similarly, you can try various functions in the live terminal given below.

JavaScript Array Live Example:

Now let’s see some JavaScript Array code live in action. In the terminal below, we have declared an array, and have implemented a loop to traverse the array. Now, please try using the above mentioned functions to see how they work. Practicing code will help you grasp the concepts faster.

Array Live Example

Array Example:

var bikes = new Array(“Yamaha”,”KTM”,”Triumph”,”Honda”); for(i=0;i<bikes.length;i++) { document.write("
“+bikes[i]); } document.write(“

Reverse order: ” + bikes.reverse() + “

“);

In this topic, we explained JavaScript Array and its functions along with various operations that are commonly performed on Array. We have covered multiple code examples to help you understand the concept.

Passing Array to a Function in C++ Programming

In this tutorial, we will learn how to pass a single-dimensional and multidimensional array as a function parameter in C++ with the help of examples.

In C++, we can pass arrays as an argument to a function. And, also we can return arrays from a function.

Before you learn about passing arrays as a function argument, make sure you know about Java Arrays and Java Function.


Syntax for Passing Arrays as Function Parameters

The syntax for passing an array to a function is:

returnType functionName(dataType arrayName[arraySize]) {
    // code
}

Let’s see an example,

int total(int marks[5]) {
    // code
}

Here, we have passed an int type array named marks to the function total(). The size of the array is 5.


Example 1: Passing One-dimensional Array to a Function

// C++ Program to display marks of 5 students

#include <iostream>
using namespace std;

// declare function to display marks
// take a 1d array as parameter
void display(int m[5]) {
    cout << "Displaying marks: " << endl;

    // display array elements    
    for (int i = 0; i < 5; ++i) {
        cout << "Student " << i + 1 << ": " << m[i] << endl;
    }
}

int main() {

    // declare and initialize an array
    int marks[5] = {88, 76, 90, 61, 69};
    
    // call display function
    // pass array as argument
    display(marks);

    return 0;
}

Output

Displaying marks: 
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69

Here,

  1. When we call a function by passing an array as the argument, only the name of the array is used.display(marks);Here, the argument marks represent the memory address of the first element of array marks[5].
  2. However, notice the parameter of the display() function.void display(int m[5])Here, we use the full declaration of the array in the function parameter, including the square braces [].
  3. The function parameter int m[5] converts to int* m;. This points to the same address pointed by the array marks. This means that when we manipulate m[5] in the function body, we are actually manipulating the original array marks.

    C++ handles passing an array to a function in this way to save memory and time.

Passing Multidimensional Array to a Function

We can also pass Multidimensional arrays as an argument to the function. For example,

Example 2: Passing Multidimensional Array to a Function

// C++ Program to display the elements of two
// dimensional array by passing it to a function

#include <iostream>
using namespace std;

// define a function 
// pass a 2d array as a parameter
void display(int n[][2]) {
    cout << "Displaying Values: " << endl;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 2; ++j) {
            cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
        }
    }
}

int main() {

    // initialize 2d array
    int num[3][2] = {
        {3, 4},
        {9, 5},
        {7, 1}
    };

    // call the function
    // pass a 2d array as an argument
    display(num);

    return 0;
}

Output

Displaying Values: 
num[0][0]: 3
num[0][1]: 4
num[1][0]: 9
num[1][1]: 5
num[2][0]: 7
num[2][1]: 1

In the above program, we have defined a function named display(). The function takes a two dimensional array, int n[][2] as its argument and prints the elements of the array.

While calling the function, we only pass the name of the two dimensional array as the function argument display(num).

Note: It is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified. This is why we have used int n[][2].

We can also pass arrays with more than 2 dimensions as a function argument.


C++ Returning an Array From a Function

We can also return an array from the function. However, the actual array is not returned. Instead the address of the first element of the array is returned with the help of pointers.

We will learn about returning arrays from a function in the coming tutorials.