Link to home
Start Free TrialLog in
Avatar of terencepires
terencepires

asked on

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
Avatar of karoldvl
karoldvl
Flag of Poland image

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

Avatar of Julian Hansen
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

ASKER CERTIFIED SOLUTION
Avatar of karoldvl
karoldvl
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of terencepires
terencepires

ASKER

Thanks !