PHP Associative Array Duplicate Keys

PHP Associative Array Duplicate Keys

No, you cannot have multiple of the same key in an associative array.

You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.

So instead of this...

42=>56 42=>86 42=>97 51=>64 51=>52

...you have this:

Array (
42 => Array ( 56, 86, 97 )
51 => Array ( 64, 52 )
)

Showing duplicate keys in associative array in PHP

You can store results as array of arrays as approach:

<?php
$arrNum = [2, 5, 6, 6, 8];

$arrNumDouble = array_map(
function($el) {
return [$el, 2*$el];
},
$arrNum
);

#var_export($arrNumDouble);

foreach($arrNumDouble as $el) {
echo "2 * $el[0] = $el[1]" . PHP_EOL;
}

share PHP code

PHP merge associative arrays with duplicate keys

Use array_replace_recursive function:

$array1 = ['Utah'=>['users'=>5],'California'=>['users'=>10]];
$array2 = ['Utah'=>['emails'=>18],'California'=>['emails'=>28]];

$result = array_replace_recursive($array1, $array2);

print_r($result);

The output:

Array
(
[Utah] => Array
(
[users] => 5
[emails] => 18
)

[California] => Array
(
[users] => 10
[emails] => 28
)
)

Update:

Though you have changed your initial requirements I also have solution for your new input data.
Used functions: array_merge and array_values

// user data
$array1 = [
['State'=>'Utah', 'users'=>5],
['State'=>'California', 'users'=>10]
];

// email data
$array2 = [
['State'=>'Utah', 'emails'=>18],
['State'=>'Arizona', 'emails'=>32],
['State'=>'California', 'emails'=>28],
];

$result = [];
foreach (array_merge($array1, $array2) as $item) {
if (isset($result[$item['State']])) {
$result[$item['State']] = array_merge($result[$item['State']], $item);
} else {
$result[$item['State']] = $item;
}
}
$result = array_values($result);

print_r($result);

The output:

Array
(
[0] => Array
(
[State] => Utah
[users] => 5
[emails] => 18
)

[1] => Array
(
[State] => California
[users] => 10
[emails] => 28
)

[2] => Array
(
[State] => Arizona
[emails] => 32
)
)

How push associative array item into associative array with duplicate keys?

As mentioned you can't have duplicate keys in an array. You could checkout array_merge_recursive() which would at least consolidate those values into a single key

$arr1 = ['foo' => 'bar'];
$arr2 = ['foo' => 'rab'];
$arr3 = ['foo' => 'pub'];
print_r(array_merge_recursive($arr1, $arr2, $arr3));

Output

Array
(
[foo] => Array
(
[0] => bar
[1] => rab
[2] => pub
)

)

Get the keys for duplicate values in an array

function get_keys_for_duplicate_values($my_arr, $clean = false) {
if ($clean) {
return array_unique($my_arr);
}

$dups = $new_arr = array();
foreach ($my_arr as $key => $val) {
if (!isset($new_arr[$val])) {
$new_arr[$val] = $key;
} else {
if (isset($dups[$val])) {
$dups[$val][] = $key;
} else {
$dups[$val] = array($key);
// Comment out the previous line, and uncomment the following line to
// include the initial key in the dups array.
// $dups[$val] = array($new_arr[$val], $key);
}
}
}
return $dups;
}

obviously the function name is a bit long;)

Now $dups will contain a multidimensional array keyed by the duplicate value, containing each key that was a duplicate, and if you send "true" as your second argument it will return the original array without the duplicate values.

Alternately you could pass the original array as a reference and it would adjust it accordingly while returning your duplicate array

Merging values of duplicate names (keys) in associative array (PHP)

Q A: No
Q B:

if(isset($baskets["apple"]))
{
$baskets["apple"] = $baskets["apple"] + VALUE
}

How do I convert a string to an associative array when the string contains a duplicate key in PHP?

Check if there's already an element in the array with the key before adding it.

    for($i=0; $i<$n; $i++)
{
if (!isset($params[$matches[1][$i]])) {
$params[$matches[1][$i]] = $matches[2][$i];
}
}
var_dump($params);

Associative Array - duplicated key values

Untested but this should do what you want using array_count_values to obtain the quantities you were looking for along with a few changes to make the script more efficient and easier to manage.

<?php
//the ids of the items the user wants to buy
$ids=$_SESSION['buy'];

//Your database of items
$menu = array(
array ('id' => '1', 'catagory' => 'newbooks','title' => 'Alex','price' => 4.95, 'desc' => 'bbbb'),
array('id' => '2','catagory' => 'newbooks','title' => 'David ','price' => 5.95, 'desc' => 'sss')
);
//Create a reverse look-up for the database
$lookUp=array();
foreach($menu as $i=>$v)$lookUp[$v['id']]=$menu[$i];



//populate the cart with items, their quantities, and a total
$cart = array();
$total = 0;
foreach (array_count_values($ids) as $id=>$quantity)
{

if (!array_key_exists($id, $lookUp))continue;
$item=$lookUp[$id];
$itemTotal=$item['price']*$quantity;
$total+=$itemTotal;
$cart[]=array_merge($item,array('quantity'=>$quantity,'itemTotal'=>$itemTotal));
}


if(count($cart) > 0)
{
echo '<table>';
echo '<tr><th>Item Description</th><th>Quantity</th><th>Price</th><th>Item Total</th></tr>';
foreach ($cart as $item)
{

echo sprintf('<tr><td>%s</td><td>%s</td><td>%0.2f</td><td>%0.2f</td></tr>',
$item["title"],$item['quantity'],$item['price'],$item['itemTotal']);
}
echo '<tr><td colspan="3" style="text-align:center;">Total</td><td>'.$total.'</td></tr>';
echo '</table>';
}


Related Topics



Leave a reply



Submit