Tag Archives: arrays

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#

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>";
  }
?>

Sorting arrays in PHP

This tutorial explains how to sort arrays in PHP. You will learn how to sort both regular arrays by their value and associative arrays by their key. You will also learn how to sort values and keys in an array in normal order (0-9,a-z) and reverse order (z-a,9-0). Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  // sorting arrays by value (using sort function)
  $heroes = array("hulk","wonder woman","superman","iron man");
  sort($heroes); // or use rsort to reverse sort
  foreach($heroes as $value){
    echo "$value </br>";
  }

  // sorting associative arrays by key (using ksort function)
  $characters = array("villain"=>"joker","hero"=>"batman");
  ksort($characters); // or use krsort to reverse sort by key
  foreach($characters as $key => $value){
    echo "The $key 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
?>

Looping through arrays with PHP

This tutorial explains how to loop through the elements in a PHP array. This works by using a for loop that will access elements in the array by their index. For each iteration of the loop, a different index will be accessed. You will also see how count() is used to count the number of elements in an array. The process for looping through each character in a string variable is basically the same as looping through each element in an array, as a string is basically an array of characters.

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

Sample PHP code to loop through each string element in an array and echo each element’s value on a new line:

<?php
  // create a new array
  $myArray = array("a","b","c");

  // loop through each element in the array
  // count will count all elements in an array
  for($i=0;$i<count($myArray);$i++){
    echo $myArray[$i] , "</br>";
  }
?>

Sample code to loop through an array and modify the value of each element in the array:

<?php
  // create a new array
  $myArray = array(1,2,3,4,5);

  // loop through each element in the array
  // count will count all elements in an array
  for($i=0;$i<count($myArray);$i++){
    // this will multiply each integer value by 2
    $myArray[$i] = $myArray[$i] * 2;
    echo $myArray[$i] , "</br>";
  }
?>

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>

Multidimensional arrays in JavaScript

This tutorial will explain how to create, access, and modify elements in a multidimensional array. In the example here, we will work with a 2D (two dimensional) array in JavaScript.

We already know that an array is a better way of storing several related values than creating multiple variables. But what if we want to store several characteristics for each element in an array? Well, we can use two dimensional arrays for that! Watch the video below to find out more and then scroll down to see the code.

In the example code below, we have a two dimensional array that stores several people in an the array. For each person, the array also stores characteristics about them including their name, age, and gender. In other words, there are elements inside elements in the array.

If we wanted to access the first element in an array we would usually use the code arrayname[0]. If we want to access the first element inside the first element of the array, we would access it using the code arrayname[0][0]. Basically, there are two dimensions in the array. We access the first element in the first dimension, and the first element from its second dimension.

Check out the code below to see how you can create a 2D array, access elements inside it, and modify values in the array.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Multidimensional Arrays</title>
 
 <script type="text/javascript">
 
 // This is 2 dimensional array which stores name, age, and gender for different people
 
 var people = [
 ["John", 16, "Male"],
 ["Mary", 42, "Female"],
 ["Jason", 21, "Male"]
 ];
 
 // Remember that array elements start counting from 0
 // To access the name of the first person in the array, we need to access people[0][0]
 document.write(people[0][0] + "<br/>");
 
 // This will access the age of the second person in the array:
 document.write(people[1][1] + "<br/>");
 
 // This will access the gender of the third person in the array:
 document.write(people[2][2] + "<br/>");
 
 // To change the age of the third person (Jason) in the array:
 people[2][1]=22;
 document.write(people[2][1] + "<br/>");
 
 // To add an extra person to the array:
 people[3]=["Sarah", 36, "Female"];
 
 // This will display all elements (name, age, gender) inside the fourth array element
 document.write(people[3]);
 
 </script>
 
</head>
<body>
 
</body>
</html>

The code above will produce output that looks like this:

Screen Shot 2015-03-20 at 10.22.59 pm


Next tutorial: 
If statements

Finding the length of arrays (and strings)

Sometimes you might need to find out how many elements exist in an array (that is, the length of the array). The sample code below shows exactly how to do that, and it also shows you how to find the length of a string using pretty much the same method.

The video here also explains how to do this.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - More Arrays</title>
 <script type="text/javascript">
 
 var cars = new Array();
 
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // to find the length (number of elements) of an array we can use arrayname.length eg.:
 
 document.write(cars.length);
 
 /* 
 We could also use the length method on a string like this:
 
 var word = "hello";
 document.write(word.length);
 
 */
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Arrays

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 and make sure you watch the video on how to use arrays here, and also the video on finding the length of arrays and strings here.

<!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
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Finding the length of arrays and strings in JavaScript

This tutorial explains how to find the length of an array (how many elements are in an array), the length of an element in an array, and the length of a string of text (how many characters in a string). You can watch the video below or click here to view it on YouTube.

Sometimes you might need to find out how many elements exist in an array (that is, the length of the array). The sample code below shows exactly how to do that, and it also shows you how to find the length of a string using pretty much the same method.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - More Arrays</title>
 <script type="text/javascript">
 
 var cars = new Array();
 
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // to find the length (number of elements) of an array we can use arrayname.length eg.:
 
 document.write(cars.length);
 
 /* 
 We could also use the length method on a string like this:
 
 var word = "hello";
 document.write(word.length);
 
 */
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Multidimensional arrays

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

Working with Strings in JavaScript

This video tutorial explains how to concatenate (join) strings, convert between integers and strings, change text to uppercase and lowercase, and also introduces indexing and arrays.

You can watch the video below or click here to view it on YouTube.  This is the fourth video from the beginners JavaScript tutorial video series.

The sample code snippet below shows how to join (concatenate) strings, find the length of a string (the number of characters in a string), convert from integer to string, display specific characters in a string, split a string up and place each word in a separate array element, and convert string to uppercase and lowercase.

Don’t try all of this in one go. Have a go at one string operation at a time and only move on to the next one when you feel comfortable to.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Strings</title>
 <script type="text/javascript">
 
 var firstName = "Nicolas";
 var lastName = "Cage";
 
 // Concatenation means joining (eg. joining two strings together to form one string
 // Below, is an example of a concatenated string being held in a variable
 var joinednames = firstName + lastName;
 
 // Below, is an example of concatention with spaces added between words.
 document.write(firstName,' ',lastName,' ',"says \"hello\".");
 
 var fullName = firstName + ' ' + lastName; // this combines two variables and a space between the strings into a new variable
 
 document.write(fullName)
 
 var nameLength = fullName.length; // this calculates the length of the string as an integer
 document.write(nameLength);
 
 var age = 20;
 document.write(fullName + age); // this prints the name string and then the variable (no spaces) 
 
 var ageString = age.toString(); // this converts the age integer variable to a string variable
 document.write(ageString);
 
 /* To convert a string to an integer, the variable must firstly contain ony numbers. It can simply be multiplied by 1 to convert to an integer
 eg. newIntVariable = stringVariable * 1
 or you can use parseInt and parseFloat functions eg parseInt('77');
 */
 
 var message = 'Hello world!';
 document.write(message.indexOf('w')) // the indexOf function finds the index number of a character in a string
 document.write(message.charAt(8)) // this gives the character at index number 8
 document.write(message.length) // this will give the length of the string
 
 var messageArray = new Array();
 messageArray = message.split(' '); //this splits the words (where there is a space) into a new array
 document.write(messageArray[0],"</br>"); // this would return "Hello" (and a new line)
 document.write(messageArray[1]); // this would return "world!"
 
 document.write(message.substring(4,8)); //this will show anything between index number 4 and 8
 document.write(message.substr(4,8)); //substr is different to substring. this will show the 8 characters after index number 4.
 
 document.write(message.toUpperCase()); // converts string to uppercase
 document.write(message.toLowerCase()); // converts string to lowercase
 document.write("<b>",message.toUpperCase(),"</b>"); // this prints the uppercase string in bold using the HTML bold element <b>
 document.write("<h1>This is a heading</h1>"); // HTML elements can be put straight into a string
 </script>
 
</head>
<body>
 
 
</body>
</html>

Next tutorial: Events