Good morning!

I have a two dimensional array, basically a table (see code below). I want to get a value from the array using two methods:
1) Using the row's key: $NewValue = $MyArray[$UniqueKey];
2) Using the row's index (row number, so to speak): $NewValue = $MyArray[$RowNumber];

The second print statement in the code below does not work. Both print statements should output the same value. Is there an easy way to do this? The table has hundreds of rows and I will not know the key value of row 879 nor can I generate it. So I cannot use array_keys(). And I DO NOT want to start at the first row and count up to the 879th row.

Any clever ideas to share and enlighten?
Thanks!

<?php
// Initialize the array keys and values
$MyArray = array();
$MyArray['first']['col1'] = 'abc'; $MyArray['first']['col2'] = 'def'; $MyArray['first']['col3'] = 'ghi';
$MyArray['second']['col1'] = 'jkl'; $MyArray['second']['col2'] = 'mno'; $MyArray['second']['col3'] = 'pqr';
$MyArray['third']['col1'] = 'stu'; $MyArray['third']['col2'] = 'vwx'; $MyArray['third']['col3'] = 'yz';
$MyArray['fourth']['col1'] = 'a1a'; $MyArray['fourth']['col2'] = 'b2b'; $MyArray['fourth']['col3'] = 'c3c';
$MyArray['fifth']['col1'] = 'ddd'; $MyArray['fifth']['col2'] = 'eee'; $MyArray['fifth']['col3'] = 'fff';
// Two methods to get a value. Second one does nothing.
print"{$MyArray['third']['col2']}</br>";
print"{$MyArray[2]['col2']}</br>";
?>

    you have associative arrays how do you expect index to work if it doesnt have one

      Yes...well that is the question 🙂

      Someone else suggested:

      print "{$MyArray['third']['col2']}</br>";
      $keys = array_keys($MyArray);
      print "{$MyArray[$keys[2]]['col2']}</br>";

      Which is clever! And works.

      But, I am wondering about the processing time in that solution. A direct lookup into an array using indexes $MyArray[$Row][$Col] versus generating an entire list of keys, direct index into it and then again into the main array. The arrays could be thousands of rows and I do alot of indexing into them.

      Any thoughts?

      So far, the array_keys approach is the only one (hence the best one :p) I've seen so far.

      Thank you for your considerations.

        The difference consists of the call to array_keys, so all you have to do is profile that.

        # create array $arr with 100k elements or some such, then
        
        $start = microtime(true);
        $keys = array_keys($arr);
        $end = microtime(true);
        
        echo 'time: ' . ($end - $start) . PHP_EOL;
        
          Write a Reply...