PHP & JS numeric and assoc arrays index trouble

This problem is probably trivial for 99% of you. So far I always tried to avoid situation like this, but now I don't have any choice.

For PHP:
$array = array();
$array[5] = 'Element';
$array['s_5'] = 'Alternative Element';
$array[7] = 'Element2';
$array['s_7 '] = 'Alternative Element2';

For JS
var array = new Array();
array[5] = 'Element';
array['s_5'] = 'Alternative Element';
array[7] = 'Element2';
array['s_7 '] = 'Alternative Element2';

And now I need to get to secondth element of array. How to do it? Of course I could create another table containing array keys for each element, or use foreach/while and do some action on specific element. Also I can get last array element in PHP using end(), but is there any other, faster way to get specific element from random array (implying I don't know keys and length of array)?

Thanks for helping me.

Answers


You might want to use a 2 dimensional array instead:

$matrix = array();
$matrix['elements'] = array();
$matrix['alt_elements'] = array();

$matrix['elements'][5] = 'Element';
$matrix['alt_elements'][5] = 'Alternative Element';

etcetera...

Avoid using associative arrays in JS. Use arrays only when the keys are numeric. Otherwise, use objects.

var matrix = {};
matrix.elements = [];
matrix.altElements = [];

matrix.elements[5] = 'Element';
matrix.altElements[5] = 'Alternative Element';

Need Your Help

API for server-side 3D rendering

api 3d render server-side

I'm working on an application that needs to quickly render simple 3D scenes on the server, and then return them as a JPEG via HTTP. Basically, I want to be able to simply include a dynamic 3D scene...

Adding whitespace to a TextView in Eclipse To Make Each Column a Fixed Length

android eclipse textview whitespace

I am using a text file that stores 3 columns of data, each having varying length.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.