简体   繁体   中英

How to access an to a value associative array using index position in PHP

With an associative array such as that one:

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");

I tried accessing to a value using :

$fruits[2];

This gives me a PHP notcie: Undefined offset;

Is there a way around that ?

Thanks

Not if you want to keep it as an associative array. If you want to use numeric key indexes you could do this:

$fruits  = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
$fruits2 = array_values($fruits);

echo $fruits2[2];

Find out more about array_values() at the PHP manual.


UPDATE: to compare two associative arrays as you mentioned in your comment you can do this (if they have the same keys -- if not you should add isset() checks):

foreach (array_keys($arr1) as $key) {
  if ($arr1[$key] == $arr2[$key]) {
    echo '$arr1 and $arr2 have the same value for ' . $key;
  }
}

Or, to avoid the array_keys function call:

foreach ($arr1 as $key => $val) {
  if ($val == $arr2[$key]) {
    echo '$arr1 and $arr2 have the same value for ' . $key;
  }
}

Here is another idea. Without more direct information about your end goal, or larger project I can't speak to any specific implementation.

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
$flavors = array( 'a' => 'crisp', 'b' => 'mushy', 'c' => 'tart' );

reset($fruit);
reset($flavors);

while (list($key, $val) = each($fruit))
{
    list( $flavorKey, $attribute ) = each( $flavors );

    echo "{$key} => {$val}<br>\n";
    echo "{$attribute}<br><br>\n";
}

[edit based on comment about array_count_values]

<?

$words = explode( " ", 'the quick brown fox jumped over the lazy yellow dog' );
$words2 = explode( " ", 'the fast fox jumped over the yellow river' );
$counts = array_count_values( $words );
$counts2 = array_count_values( $words2 );

foreach( $counts as $word => $count )
{
    if ( array_key_exists( $word, $counts2 ) && $counts2[$word] == $counts[$word] )
    {
        echo $word . ' matched.<br>';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM