Find value in array, then add value after that key

Hi there,

i'm having a little problem on a script here :
I have to
- find a value recursively inside an array (done)
- then add data right after the value i just found in the array (this is why i need help)

I could use array_push, but that would put data at the end of the array, i want it be put right after the data, shifting down all following values indexes

any leads ?


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Please see if this is what you want:

$myArray = array(0 => 'A',
				 1 => 'B',
				 2 => 'C',
				 3 => 'D',
				 4 => 'F',
				 5 => 'G',

$pos = 4;
$length = count($myArray);

$before = array_slice($myArray, 0, $pos);
$after = array_slice($myArray, $pos, $length-$pos);

$insert = array(0 => 'E');

$myArray = array_merge($before, $insert, $after);



Open in new window

Julian HansenCommented:
Why not append the key and then sort the array?

$myArray[] = 'E';

Alternatively see code

Why not append the key and then sort the array?

$myArray[] = 'E';


$newArray = array();
$insertElement = 'E';
foreach($myArray as $v)
    if (stricmp($v, $insertElement) > 0)) $newArray[] = $insertElement;
    $newArray[] = $v;

Open in new window

I doubt we can count on the array in question being pre-sorted. That was just my dummy data that goes as alphabet so that it's easy to see.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
terencepiresAuthor Commented:
Thanks !
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.