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 ?

Cheers,

Terence
LVL 1
terencepiresAsked:
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.

karoldvlCommented:
Please see if this is what you want:
<?php

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

$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);

print_r($myArray);

?>

Open in new window

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

$myArray[] = 'E';
sort($myArray);

Alternatively see code


Why not append the key and then sort the array?

$myArray[] = 'E';
sort($myArray);

Alternatively

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

Open in new window

0
karoldvlCommented:
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.
0

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 !
0
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
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.