Showing posts with label arrays. Show all posts
Showing posts with label arrays. Show all posts

Wednesday, July 7, 2010

Get length of associative arrays in Javascript

When you make an associative array in Javascript, it is not that straightforward to get the length of the array. Example:
Code:
  1. var ar = new Array();
  2. ar['nice'] = "hello";
  3. alert(ar.length);
  4. //keeps on giving zero

This is because associative arrays are treated like objects and hence they do not have the "length" attribute. To traverse through the array, you can use this:
Code:
  1. var ar_ct = 0;
  2. var ar = new Array();
  3. ar['nice'] = "hello";
  4. for (i in ar)
  5. {
  6. alert(ar[i]); // value is "hello"
  7. }

Tuesday, September 15, 2009

Sunday, March 15, 2009

PHP Arrays

Here are some of the useful facts and functions about arrays in PHP. Content of this post is summarized from Programming PHP by Kevin Tatroe and Rasmus Lerdorf. You can find the online version of this chapter here.

Indexed Vs Associative Arrays
PHP allows you to declare 2 kinds of array: Indexed and Associative. An indexed array means that the elements in the array are "indexed" or referred to by position in the array. To refer to the i-th element in the array, you simply call $arr[i-1](assuming $arr is the array name).

Elements in an associative array are key-value pairs. The keys are unique, so you cannot have two elements with the same key. An example of an associative array would be {'Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00}. To find out the "value" of Gasket, we use $arr['Gasket'].

Define Arrays

$addresses = array( );

Constructs an empty array

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');

Initializes an indexed array

$price = array(
'Gasket' => 15.29,
'Wheel' => 75.25,
'Tire' => 50.00);

Initializes an associative array

Append Values to the End of Array
$family = array('Fred', 'Wilma');
$family[] = 'Pebbles'; // $family[2] is 'Pebbles'
Note that appending like this to an associative array might not yield the desired result.
$person = array('name' => 'Fred');
$person[] = 'Wilma'; // $person[0] is now 'Wilma'

Find Array Length
Use sizeof($arr)or count($arr). This works for both indexed and associative arrays.

Chapter 5 (Arrays) of the Programming PHP book offers an extensive range of array manipulation functions. You may want to check it out.