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
)
2
  • You can't have two array elements with the same key, explain better what you need to do. Commented Apr 22, 2010 at 9:04
  • i want to duplicate one element! generate a new key with the value i want to duplicate! Commented Apr 22, 2010 at 9:08

3 Answers 3

1

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
)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

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

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.