Home / Archive by tag 'arrays'

Posts tagged "arrays"

Creating multidimensional arrays in Javascript

There are two ways of creating an array of arrays or multidimensional arrays in Javascript.

Declaring individual arrays:

var oneArray = new Array(2300, 3105, 2909, 4800);
var twoArray = new Array(1800, 1940, 2470, 4350);
var threeArray = new Array(900, 1200, 1923, 3810);

Create multidimensional array from individual arrays:

var allArray = new Array(oneArray, twoArray, threeArray);

The most compact array creation approach is to use the bracket shortcuts exclusively:

var allArray = [
		[2300, 3105, 2909, 4800],
		[1800, 1940, 2470, 4350],
		[900, 1200, 1923, 3810]
	       ];

Add element to end of array in Javascript

you can use the length property of the array to get the index of the last item in an array. The length integer is always one larger than the highest zero-based index value of the array, hence the length value can act as the index for the next item.

Declare array:

var myArray = new Array();
myArray[0] = "Mani";
myArray[1] = "Kaka";

Append new item at the end of the array:

myArray[myArray.length] = "newitem";

Creating an Array in Javascript

There are two ways in JavaScript (a long way and a shortcut) to generate and populate an array.
One is to use the Array object constructor.
Example:

var myArray = new Array();
myArray[0] = "Mani";
myArray[1] = "Kaka";

You can also pass a parameter to the constructor to tell it about the size of array. The created array elements will be initialized to NULL.
Example:

var myArray = new Array(12);

You can also pass data to the constructor to create an array directly.
Example:

var myArray = new Array("Mani", "Kaka", "Biryani");

The shortcut approach is to use square brackets to symbolize the array constructor:
Example:

var myArray = ["Mani", "Kaka", "Biryani"];

codeigniter form_hidden() with arrays

Syntax:
form_hidden(array_hidden);

Return Type:
string.

Description
form_hidden() is used to create hidden input types from arrays

Example:

$hidden = array ("parent_id" => "0");

Output:

<input type="hidden" id="parent_id" value="0"/>

Create array from JSON string in EXTJS

This example demonstrates how to re-create the array based on its JSON string. Take the JSON representation of foodArray:

var foodJson = '["Dal","Naan","Rice"]';

Parse the JSON and rebuild the array:

var foodArray = Ext.decode(foodJson);

Output values in the array:

foodArray[0] = 'Dal';
foodArray[1] = 'Naan';
foodArray[2] = 'Rice';

Encode array to JSON in EXTJS

1. Create an array called foodArray:

var foodArray = new Array();

2. Add values in the array:

foodArray[0] = 'Dal';
foodArray[1] = 'Naan';
foodArray[2] = 'Rice';

3. Now, convert to JSON:

var foodJson = Ext.encode(foodArray);

Scalar function in perl

PERL’s scalar function returns different output when used with lists.

Example Using ‘scalar’ with arrays:

                my @array = ('a','b','c'); 
                my $valueReturned = scalar (@array); 
                print "Value Returned : $valueReturned";

Output :
Value Returned : 3

Example using ‘scalar’ with lists:

                my $valueReturned = scalar ('a', 'b', 'c'); 
                print "Value Returned : $valueReturned";

Output :
Value Returned : c

When used with arrays it will always return the number of elements in the same. But when used with lists it will return the last element in it.

Author: Purva Adhatrao


Generic algorithm to reverse array elements

public static void ReverseArray<T>(this T[] inputArray)
{
	T temp = default(T);
 
	if (inputArray == null)
		throw new ArgumentNullException("inputArray is empty");
 
	if (inputArray.Length > 0)
	{
		for (int counter = 0; counter < (inputArray.Length / 2); counter++)
		{
			temp = inputArray[counter];
			inputArray[counter] = inputArray[inputArray.Length - counter - 1];
			inputArray[inputArray.Length - counter - 1] = temp;
		}
	}
	else
	{
		Trace.WriteLine("Reversal not needed");
	}
}

Reversing an array in CSharp (C#)

An efficient method to reverse the order of elements within an array using csharp would be to use the reverse() method of the Array class.

int[] someArray = new int[5] {1,2,3,4,5};
Array.Reverse(someArray);

Generically swapping two elements in array using C#(Csharp)

There is no built-in function in csharp (C#) to swap array elements. Below is an example of a generic array element swap function.

public static void SwapArrayElements<T>(this T[] inputArray, int index1, int index2)
{
T temp = inputArray[index1];
inputArray[index1] = inputArray[index2];
inputArray[index2] = temp;
}

Example of swapping elements:

public static void TestSwap( )
{
int[] someArray = {1,2,3,4,5};
for (int counter = 0; counter < someArray.Length; counter++)
{
	Console.WriteLine("Element " + counter + " = " + someArray[counter]);
}
 
someArray.SwapArrayElements(0, 4);
 
for (int counter = 0; counter < someArray.Length; counter++)
{
	Console.WriteLine("Element " + counter + " = " + someArray[counter]);
}
}

Array of objects in C#

Class declaration:

public class person
	{
		String name;
		int age;
 
		public person(String inName, int inAge)
		{
			name = inName;
			age = inAge;
 
		}
 
		public string getName()
		{
			return name;
		}
	}

Array of objects of type person:

person[] funnyGuys = new person[3];
funnyGuys[0] = new person("mani", 38);
funnyGuys[1] = new person("kak", 36);
funnyGuys[2] = new person("shah", 35);
 
for (int i = 0; i != funnyGuys.Length; i++) 
{
	Console.WriteLine(funnyGuys[i].getName() + " is the person");
}

Declare arrays, find length and display arrays in c#

declare an array, fill an array.

string[] names = new string[3];
names[0] = "mani";
names[1] = "kak";
names[2] = "shah";

find the length of an array

int len = names.Length;
Console.WriteLine("It is " + len + " long.");

dump an array

for (int i = 0; i != names.Length; i++) 
{
     Console.WriteLine(names[i])
}

XML-RPC Array Data Type

In XML-RPC, Numerically indexed arrays are passed as a single structure within the value element. Arrays are defined with a specific structure of child elements.

Example Declaration:

<params>
<param>
<value>
	<array>
		<data>
			<value><string>Two</string></value>
			<value><boolean>1</boolean></value>
			<value><double>42.307400</double></value>
		</data>
	</array>
</value>
</param>
</params>

The array tag defines the value of the parameter as an array, and the data tag indicates the start of array data. There is a value element for each item in the array and they may have children elements that define the data type of the value. Arrays can be recursive. Within each value element, can be another array as long as they contain the array/data/value descendant sequence.


Read a file into an array using PHP

A file can be read into an array using the file() php function. The file function reads all the lines of a file and populates each line as a value in an array, and returns the array

Example code on how to use file():

<?php 
$lines = file("/tmp/file.txt");
foreach ($lines as $line) {
  $line = rtrim($line);
  print("$line\n");
  # more statements...
}
?>

The file() function breaks lines right after the new line character “\n”. Each line will contain the “\n” at the end. The rtrim() function is used to remove “\n”.


Iterate over array using key, value, current, next and prev php functions

The most direct way of manipulating the pointer of an array is by using a series of functions designed specifically for this purpose. Upon starting an iteration over an array, the first step is usually to reset the pointer to its initial position using the
reset() function; after that, we can move forward or backwards by one position by using prev() and next() respectively. At any given point, we can access the value of the current element using current() and its key using key().

Example code:

$array = array(’foo’ => ’bar’, ’baz’, ’bat’ => 2);
function displayArray(&$array) {
reset($array);
while (key($array) !== null) {
echo key($array) .": " .current($array) . PHP_EOL;
next($array);
}
}

Accessing global variables in PHP

There are two ways of accessing variables defined in a global scope from within a function scope. We can use the global statement or the $GLOBALS array.

Example code using global statement:

$a = "Namaste";
$b = "World";
function hello()
{
global $a, $b;
echo "$a $b";
}
hello(); // Displays "Namaste World"

Example code using $GLOBALS array:

$a = "Namaste";
$b = "World";
function hello()
{
echo $GLOBALS[’a’] .’ ’. $GLOBALS[’b’];
}
hello(); // Displays "Namaste World"

Find a specific value in an array using PHP

Two functions can be used to test if a value is defined in an array.

array_search($value, $array)

Returns the first key of the matching value in the array, if found. Otherwise, it returns false.

in_array($value, $array)

Returns true if the $value is defined in $array.

Example code for arrary_search():

<?php 
$array = array("Perl", "PHP", "Java", "PHP");
print("Search 1: ".array_search("PHP",$array)."\n");
print("Search 2: ".array_search("Perl",$array)."\n");
print("Search 3: ".array_search("C#",$array)."\n");
print("\n");
?>

Output:
Search 1: 1
Search 2: 0
Search 3:


Test if a Key is defined in an array using PHP

Two functions can be used to test if a key is defined in an array.

array_key_exists($key, $array)

Returns true if the $key is defined in $array.

isset($array[$key])

Returns true if the $key is defined in $array.

Example code:

<?php 
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print("Is 'One' defined? ".array_key_exists("One", $array)."\n");
print("Is '1' defined? ".array_key_exists("1", $array)."\n");
print("Is 'Two' defined? ".isset($array["Two"])."\n");
print("Is '2' defined? ".isset($array[2])."\n");
?>

Output:

Is ‘One’ defined? 1
Is ’1′ defined?
Is ‘Two’ defined? 1
Is ’2′ defined?


Get the total number of items in an array using PHP

The total number of values in an array can be obtained by using the php count() function.

Example code:

<?php 
$array = array("PHP", "Perl", "Java");
print_r("Size 1: ".count($array)."\n");
$array = array();
print_r("Size 2: ".count($array)."\n");
?>

Output:

Size 1: 3
Size 2: 0

count() has an alias called sizeof().


Sorting numerically indexed arrays with php sort()

The sort() function sorts an array. Elements will be arranged from lowest to highest when this function has completed. It accepts an array as its argument and sorts it either alphabetically if any strings are present or numerically if all elements are numbers. The function doesn’t return any data, transforming the array you pass it.

Example code:

 
$alpha = array ("x", "a", "f", "c");
sort( $alpha );
 
foreach ( $alpha as $var ) {
  print "$var<br />";
}

sort() does not work on associative arrays. The values will be sorted as expected but keys in associative arrays will be lost and replaced by numerical indices that follow the sort order. rsort() can be used to reverse sort a numerically indexed array in exactly the same way as sort().