Tag Archives: array

Arrays in C#

Arrays are basically a list of items of the same type that are grouped together in a single container. Unlike variables which can only contain one value at a time, arrays can contain many different values of the same type (eg. string, or integer). This tutorial explains how to create arrays, access elements in an array, and use for loops to work through the elements in arrays.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};
      // Create an array of int type
      int[] ages = {26,18,49,33};
      // Display second item in names array (array indexing starts at 0)
      Console.WriteLine(names[1]);
      // Display fourth item in ages array
      Console.WriteLine(ages[3]);
      // Store the names array's length (number of elements in array) in variable
      int arrayLength = names.Length;
      // Display names array's length
      Console.WriteLine(arrayLength);
      // Go through each element in names array and check if Sam exists in array
      for (int i = 0; i < arrayLength; i++) {
        if (names[i] == "Sam") {
          Console.WriteLine("Sam is here!");
        }
      }
    }
  }
}

Next tutorial: Foreach loops in C#

Passing an array into a function with PHP

This tutorial explains how to pass an array as an argument in a function with PHP. The process of passing an array into a function is very much the same as passing a variable into a function. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  // create the 'scores' array
  $scores = array(9,7,112,89,633,309);

  // create the 'average' function
  function average($array){
    // set 'total' to 0
    $total = 0;
    foreach($array as $value){
      // adds the value of each item in the array, one by one
      $total += $value;
    }
    // calculate the average and return the result
    return $total/count($array);
  }

  // call the 'average' function and use the 'scores' array as argument
  echo "Average = ", average($scores);
?>

Slicing (splitting) and merging arrays in PHP

This tutorial explains how to splice (split) an array into more than one array by specifying a new array and where to split the existing array, and also how to merge two arrays into a single array. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  // slicing (splitting) arrays using the array_slice function
  $heroes = array("hulk","wonder woman","superman","iron man");
  $new_heroes = array_slice($heroes,1,3);
  foreach($new_heroes as $value){
    echo "$value </br>";
  }

  // merging arrays using the array_merge function
  $more_heroes = array("spider-man","batman");
  $all_heroes = array_merge($heroes,$more_heroes);
  foreach($all_heroes as $value){
    echo "$value </br>";
  }
?>

Array extract function in PHP

This tutorial explains how to use the extract function in PHP on an array. The extract function is used to turn array elements into variables. It works on only associative arrays – the key becomes the variable name and the value for that key becomes the value of the new variable. Watch the video below and then scroll down for the sample code.

Sample PHP code:

<?php
  // The extract function turns array elements into variables
  // It works on associative arrays - the key becomes the variable name
  // and the value for that key becomes the value of the new variable.
  $characters = array('hero'=>'batman','villain'=>'joker');
  extract($characters);
  echo $hero , "</br>";
  echo $villain
?>

Array implode and explode functions in PHP

This tutorial shows how to use the implode and explode functions on arrays in PHP. The implode function is used to turn an array into a string, whereas the explode function is used to turn a string into an array. Watch the video below and then scroll down to see the commented sample code.

Sample PHP code:

<?php
  $avengers = array("Iron Man","Thor","Hulk","Hawkeye","Black Widow");
  // implode - turns an array into a string
  $avengersString = implode(' ',$avengers);
  // implode(' ',$avengers); will add a space between each array item in the new string

  echo $avengersString; // displays the string

  // explode - turns a string into an array
  $superheroesString = "wolverine,batman,hulk,spider-man,storm,iron man";
  $superheroesArray = explode(',',$superheroesString);
  // explode(',',$superheroesString); will add each item occuring after a comma in
  // the string as a separate element in the array.

  echo $superheroesArray[5]; //displays the 6th element in the array
?>

Foreach loops in PHP

This tutorial explains how to use the foreach loop to loop through each item (element) in an array. The foreach loop can only be used on arrays and objects in PHP. On each iteration of a foreach loop, the value of the current element being accessed is assigned to $value. Foreach loops can be used on both regular arrays and associative arrays.

Watch the video below and then scroll down to see the sample code.

The sample PHP code below shows how to use a foreach loop for both regular arrays and associative arrays:

<?php
  $normal_array = array("Mary","Bob","Joe","Tim");
  $assoc_array = array("Sarah"=>25,"Kim"=>18,"Alice"=>32,"Alan"=>17);

  // using a foreach loop on a regular array:
  foreach($normal_array as $value){
    echo "Name: $value</br>";
  }

  // using a foreach loop on an associative array:
  foreach($assoc_array as $key => $value){
    echo "$key's age is $value.</br>";
  }
?>

Associative arrays in PHP

An associative array is an array that use keys instead of index numbers for each element in the array. Keys in the array are given a value. Keys can only be used once in the array. The syntax looks like this:

$array = array("key"=>value,"anotherkey"=>value);

To access an element in the associative array, you access it by its key (not its index). For example, $array[“key”]; instead of $array[0];

Watch the video below to see how you can create and use associative arrays and then scroll down to view the sample code.

Sample PHP code:

<?php
  // Associative arrays are arrays that use keys instead of index numbers
  // Every key has a value. Keys can only be used once.
  $ages = array("Jim"=>25,"Sam"=>18,"Alice"=>19,"Sarah"=>23);
  $echo $ages["Jim"]; // will echo Jim's age value
  print_r($ages); // will print all keys in the array and their values
?>

Modify existing values in a PHP array

This tutorial explains how to modify existing values in a PHP array. It’s pretty simple – all you need to do is refer to the array and its index and then change that index’s value with another value.

Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  // create a simple array with 12 elements inside it
  $months = array("January","February","March","April","May","June","July","August","September","October","November","December");
  
  // change the value of the second element in the array
  $months[1] = "Feb";

  // return the value of the second element in the arrray
  echo $months[1];
?>

Arrays in PHP

An array is a structured data type that contains a number of related data items. It is kind of like a list eg. $months = array(0,1,2,3,4,5); creates an array that contains 6 different numbers.

Each item in the array has an index number which represents its position in the array. Indexing begins from 0 which means that the first value in an array will have an index of 0, the second value will have an index of 1, the third value will have an index of 2, and so on.

This tutorial explains how to create arrays in PHP and how to add elements and view elements in arrays. You will also learn how to add more items to an existing array using the array_push function.

In the video tutorial you are also introduced to print_r and var_dump. Here are the differences between echo, print, print_r, and var_dump:

  • echo – outputs all of the parameters. It is a language construct, not a function.
  • print – is mostly the same as echo. However, print has a return value of 1 meaning it can be used in expressions whereas echo has a void return type.
  • print_r – displays information about a variable or array that is readable by humans.
  • var_dump – prints out a detailed ‘dump’ of a variable or array. A dump includes information such as the type of variable or array and its size. A dump also includes the type and size of individual elements in an array. var_dump provides more detail that print_r does. More information can be found here.

Sample PHP code:

<?php
  // create a simple array with 6 elements inside it
  $months = array('January','February','March','April','May','June');

  // use array_push to add 1 or more items to the array
  array_push($months,'July','August','September','October','November','December');

  // return the value of the twelfth element in the array
  echo $months[11];

  // display the values in the array and their key
  print_r(array_values($months));

  // display the values in the array as well as the size of the array
  // and the size of each element in the array
  var_dump(array_values($months));
?>

PHP Manual references:

Introduction to JSON

JSON stands for JavaScript Object Notation. JSON is a light-weight data interchange format that uses JavaScript syntax in text format that can be read and used as data by other programming languages.

In this example, we will use JSON to define an object with an array of records – we will use the Avengers characters for this example. Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>JSON</title>
</head>
 
<body>
<h2>The Avengers</h2>
 
<p id="avengerstext"></p>
 
<script>
var text='{"avengers":['+
'{"firstName":"Bruce","lastName":"Banner"},'+
'{"firstName":"Tony","lastName":"Stark"},'+
'{"firstName":"Natalia","lastName":"Romanova"},'+
'{"firstName":"Thor","lastName":"Odinson"}]}';
 
obj = JSON.parse(text);
document.getElementById("avengerstext").innerHTML=obj.avengers[0].firstName+" "+obj.avengers[0].lastName+"<br>"+obj.avengers[1].firstName+" "+obj.avengers[1].lastName+"<br>"+obj.avengers[2].firstName+" "+obj.avengers[2].lastName+"<br>"+obj.avengers[3].firstName+" "+obj.avengers[3].lastName;
 
</script>
 
</body>
</html>

Sample code: Using jQuery to push array elements into an HTML table

The sample code shows how to use jQuery to push the elements inside a 2D array into an HTML table. If you are not familiar with jQuery, click here to find out more about the jQuery library.

Note that the code below links to the jQuery 2.1.0 library which is hosted on the jQuery website. You can download this file and store it locally or upload it to your own site so that you don’t have to hot-link to the jQuery website.

Here is the code:

<!DOCTYPE html>
<html>
<head>
 <title>Putting JS array elements into a table using jQuery</title>
 
 <script type='text/javascript' src='//code.jquery.com/jquery-2.1.0.js'></script>
 <script type='text/javascript'>
 $(window).load(function(){
 var itemsArray = [];
 itemsArray[0] = ["a","b","c"];
 itemsArray[1] = ["d","e","f"];
 itemsArray[2] = ["g","h","i"];
 itemsArray[3] = ["j","k","l"];
 itemsArray[4] = ["m","n","o"];
 itemsArray[5] = ["p","q","r"];
 itemsArray[6] = ["s","t","u"];
 itemsArray[7] = ["v","w","x"];
 itemsArray[8] = ["y","z",];
 
 var table = $('#myTable');
 var row, cell;
 for(var i=0; i<itemsArray.length; i++){
 row = $( '<tr />' );
 table.append( row );
 for(var j=0; j<itemsArray[i].length; j++){
 cell = $('<td>'+itemsArray[i][j]+'</td>')
 row.append( cell );
 }
 }
 
 });
 
</script>
 
 
</head>
<body>
 <table id="myTable">
</table>
 
</body>
 
 
</html>

This will be the result of the code above:

Screen Shot 2015-03-21 at 11.31.11 am

Looping through arrays (and strings)

By now you should be familiar with both arrays and for loops. In this tutorial we are going to use both of these coding concepts. We can easily use a for loop to loop through each element in an array.

Watch the video below and then scroll down the page to access the code which you can use yourself.

In the sample code below, we will loop through every member of the Simpsons family and print each family member on a new line. Each family member is an element in simpsonsArray and the arrayLength variable stores the length of the simpsonsArray (the number of elements in the array) as a number value. There are five elements in the array so there will be five iterations of this for loop.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // This example shows how to loop through an array
 var simpsonsArray = ["Homer","Marge","Bart","Lisa","Maggie"]; // this is the array
 var arrayLength = simpsonsArray.length; // this variable stores length of the array (no. of elements in array)
 for (i = 0; i < arrayLength; i++) {
 document.write(simpsonsArray[i],"</br>"); // this will show each family member on a new line
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

We can also loop through every character in a string variable too. The code below loops through every letter in the word variable and displays each letter on a new line.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // This example shows how to loop through each character in a string
 var word = "Hello"; // this is the string variable
 var wordLength = word.length; // we use the length method to store the length of the word string in a variable
 for (i = 0; i < wordLength; i++) {
 document.write(word[i],"</br>"); // this will show each letter of the word on a new line
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Objects, properties and methods

Arrays in JavaScript

This tutorial explains how to set up and access the elements in an array in JavaScript. An array is a data structure which, unlike variables, can store more than one value. For example, an array could store several string values or several numbers. Each element in an array is separated by a comma and all of the elements are stored inside square brackets eg. numbers = [1,2,3,4,5];

You can watch the video below to see how to create and use arrays and scroll down to see the sample code.

Arrays are very useful in any programming language. When you use a simple variable, you can only store one value. For example age = 17 or name = “Harry”. But what if you want to store a list of related values such as all the names of members in a family? That is where arrays come in handy. Take a look at the syntax in the sample code below.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Arrays</title>
 <script type="text/javascript">
 
 // how to declare and initialise an array when you know the values
 var words = new Array("hello","hi","howdy","gday");
 
 // how to print an element from an array
 document.write(words[2]);
 
 // you can also declare an array by specifying the number of elements in the array without adding them eg.
 var pets = new Array(4);
 // and then add values later eg.
 pets[0]= "dog";
 pets[1]= "cat";
 pets[2]= "fish";
 pets[3]= "bird";
 
 // you can also start off with an empty array eg.
 
 var cars = new Array();
 
 // and then add values later
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // Some array hints:
 // each value is an element in an array
 // array elements are accessed using an index which starts from 0
 
// A shorter way of creating an array of integers:
var myNumbers = [1,2,3,4,5];
 
// A shorter way of creating an array of strings:
var myStrings = ["a","b","c"];
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Finding the length of arrays and strings