Reputation: 4810
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
Upvotes: 3
Views: 1659
Reputation: 1822
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>';
}
}
Upvotes: 1
Reputation:
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;
}
}
Upvotes: 8