2

I have an array already existing. Lets say it has 3 items.

$user = array('people' => 5, 'friends' => 10, 'siblings' => 7);

I can then access this array like,

echo $user['people']; // 5
echo $user['friends']; // 10

Now lets say I have another array called $person like,

array(3) { 
           [0]=> array(2) 
         { [0]=> string(4) "people" [1]=> string(1) "30" } 
           [1]=> array(2) 
         { [0]=> string(6) "friends" [1]=> string(1) "22" } 
           [2]=> array(2) 
         { [0]=> string(10) "siblings" [1]=> string(1) "71" }
         }

I can access my $user array by using the second array $person manually by doing.

 echo $user[$person[0][0]]; // Is accessing $user['people'], 5
 echo $user[$person[0][1]]; // Is accessing $user['friends'], 10
 echo $user[$person[0][2]]; // Is accessing $user['siblings'], 7

How can I do this dynamically (as the $person arrays keys can change)? Let us say to use it in a function like so,

max($user[$person[0][0]], $user[$person[0][1]], $user[$person[0][2]]) // 10

If this possible?

2
  • Is echo $user[$person[0][3]]; really printing content of $user['siblings'] ? I think it should be echo $user[$person[0][2]]; Commented Jan 23, 2012 at 18:28
  • Ooops my bad!? Just a typo lol Commented Jan 23, 2012 at 18:29

3 Answers 3

2

use a foreach() :

foreach($person as $key => $value)
{
  echo $value[$key];
}
Sign up to request clarification or add additional context in comments.

3 Comments

And how would I go about dynamically adding it to the max function, that is where I am stuck at. The array $person could have as many keys as 100.
@cgwebprojects The max() function takes either a set of arguments or one array argument - so you would just build a temporary array and pass that to max()
@cgwebprojects: you can find here: stackoverflow.com/questions/5846156/…
1

A more robust solution than a foreach hard-coded for a two-dimensional array would be PHP's built-in RecursiveArrayIteratordocs:

$users = array(
  array('people' => 5, 'friends' => 10, 'siblings' => 7),
  array('people' => 6, 'friends' => 11, 'siblings' => 8),
  array('people' => 7, 'friends' => 12, 'siblings' => 9)
);

$iterator = new RecursiveArrayIterator($users);

while ($iterator->valid()) {
  if ($iterator->hasChildren()) {
    // print all children
    foreach ($iterator->getChildren() as $key => $value) {
      echo $key . ' : ' . $value . "\n";
    }
  } else {
    echo "No children.\n";
  }
  $iterator->next();
}

Comments

0

Try using a foreach loop with $user[$person[0]] as the array parameter. If you want to go through both levels of the multidimensional array, you can nest a foreach inside of another foreach

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.