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';