views:

47

answers:

3

how i can duplicate one element from array:

for example, i have this array:

Array
(
    [LRDEPN] => 0008.jpg
    [OABCFT] => 0030.jpg
    [SIFCFJ] => 0011.jpg
    [KEMOMD] => 0022.jpg
    [DHORLN] => 0026.jpg
    [AHFUFB] => 0029.jpg
)

if i want to duplicate this: 0011.jpg , how to proceed?

i want to get this:

Array
(
    [LRDEPN] => 0008.jpg
    [OABCFT] => 0030.jpg
    [SIFCFJ] => 0011.jpg
    [NEWKEY] => 0011.jpg
    [KEMOMD] => 0022.jpg
    [DHORLN] => 0026.jpg
    [AHFUFB] => 0029.jpg
)
+1  A: 

EDIT:

Looks like you modified your question :)

If you want to have a new key with the duplicated value you can do:

$array_name['NEWKEY'] = $array_name['SIFCFJ']

Old answer:

You cannot.

An array cannot have multiple values with same key.

$arr = array();
$arr['foo'] = 'bar1';
$arr['foo'] = 'bar2'; // this will wipe out bar1

And if you try to duplicate:

$arr = array();
$arr['foo'] = 'bar1';
$arr['foo'] = 'bar1';

you'll be overwriting the value bar1 associated with key foo with bar1 itself. The array will have 1 key value pair not 2.

codaddict
ok!i understand, i edited the question! i will generate a new key, but i want the value to be the same!
robertdd
@robertdd: Having a new key with the old value is possible. I've updated my answer.
codaddict
how i cand add the $array_name['NEWKEY'] right after $array_name['SIFCFJ']?
robertdd
A: 
$arr['newkey'] = $arr['oldkey'];
natsort($arr);
oezi
A: 

Something like the following, change the uniqid() function to yours:

<?php

$a=array(
    'LRDEPN' => '0008.jpg',
    'OABCFT' => '0030.jpg',
    'SIFCFJ' => '0011.jpg',
    'KEMOMD' => '0022.jpg',
    'DHORLN' => '0026.jpg',
    'AHFUFB' => '0029.jpg'
);

$i='0011.jpg';

$newArray=array();
foreach($a as $k=>$v){
    $newArray[$k]=$v;
    if($v==$i) $newArray[uniqid()]=$v;
}

print_r($newArray);

?>

Which gets you:

Array
(
    [LRDEPN] => 0008.jpg
    [OABCFT] => 0030.jpg
    [SIFCFJ] => 0011.jpg
    [4bd014ebf3351] => 0011.jpg
    [KEMOMD] => 0022.jpg
    [DHORLN] => 0026.jpg
    [AHFUFB] => 0029.jpg
)
zaf