Array_Splice() For Associative Arrays

array_splice() for associative arrays

I think you need to do that manually:

# Insert at offset 2
$offset = 2;
$newArray = array_slice($oldArray, 0, $offset, true) +
array('texture' => 'bumpy') +
array_slice($oldArray, $offset, NULL, true);

array_splice() - Numerical Offsets of Associative Arrays

Just grabbing and unsetting the value is a much better approach (and likely faster too), but anyway, you can just count along

$result = array();
$idx = 0; // init offset
foreach ($input as $key => $value)
{
if ($key == 'more')
{
// Remove the index "more" from $input and add it to $result.
$result[] = key(array_splice($input, $idx, 1));
}
$idx++; // count offset
}
print_R($result);
print_R($input);

gives

Array
(
[0] => more
)
Array
(
[who] => me
[what] => car
[when] => today
)

BUT Technically speaking an associative key has no numerical index. If the input array was

$input = array
(
'who' => 'me',
'what' => 'car',
'more' => 'car',
'when' => 'today',
'foo', 'bar', 'baz'
);

then index 2 is "baz". But since array_slice accepts an offset, which is not the same as a numeric key, it uses the element found at that position in the array (in order the elements appear), which is why counting along works.

On a sidenote, with numeric keys in the array, you'd get funny results, because you are testing for equality instead of identity. Make it $key === 'more' instead to prevent 'more' getting typecasted. Since associative keys are unique you could also return after 'more' was found, because checking subsequent keys is pointless. But really:

if(array_key_exists('more', $input)) unset($input['more']);

Array_splice to swap an element with previous in a multidimensional associative array


The element from it's position(N) to go to position(N-1)
I want the element at position(N-1) to go at position(N),

All you say is that you want to swap the two, where N is never 0 in a zero indexed array.

Move Element N to N-1:

/** 
* [0] is top
*/
function moveUp(&$array, $n) {
if ($n < 1) throw new InvalidArgumentException();
if (!isset($array[$n])) throw new InvalidArgumentException();
// taking out at $n
$out = array_splice($array, $n, 1);
// adding in at $n - 1
array_splice($array, $n - 1, 0, $out);
}

Usage:

$n = 2;
moveUp($array, $n);
var_dump($array);

Because the element at N-1 will get one element added in front, it will automatically move to N. Job done. array_splice is really powerful.

How to add an array value to the middle of an associative array?

Am I missing something?

$key = 'z';
$offset = array_search($key, array_keys($array));

$result = array_merge
(
array_slice($array, 0, $offset),
array('c' => 3),
array_slice($array, $offset, null)
);

Handling of nonexistent keys (appending $data by default):

function insertBeforeKey($array, $key, $data = null)
{
if (($offset = array_search($key, array_keys($array))) === false) // if the key doesn't exist
{
$offset = 0; // should we prepend $array with $data?
$offset = count($array); // or should we append $array with $data? lets pick this one...
}

return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}

Demo:

$array = array('a' => 1, 'z' => 2, 'd' => 4);

// array(4) { ["a"]=> int(1) ["c"]=> int(3) ["z"]=> int(2) ["d"]=> int(4) }
var_dump(insertBeforeKey($array, 'z', array('c' => 3)));

// array(4) { ["a"]=> int(1) ["z"]=> int(2) ["d"]=> int(4) ["c"]=> int(3) }
var_dump(insertBeforeKey($array, 'y', array('c' => 3)));

How to insert element into arrays at specific position?

array_slice() can be used to extract parts of the array, and the union array operator (+) can recombine the parts.

$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:


Array
(
[zero] => 0
[one] => 1
[two] => 2
[my_key] => my_value
[three] => 3
)

PHP - Need help inserting arrays into Associative arrays at given keys

Ok, after playing with it for quite some time, I finally got it working the way I want it. I am using certain keys within the $new_menu_buttons to decide on what to do. e.g.: position tells me if it is after or before, parent tells me where to search for the key at, and slug gives me the key to use for each new menu array that gets added. array_splice isn't working for me, so I'm using the array_merge approach instead which works just great. Here it is for anyone else who gets stuck with this problem.

function array_insert_buttons($buttons, $new_menu_buttons)
{
foreach($new_menu_buttons as $new)
{
$keys = array_keys($buttons);
$position = (int)array_search($new['parent'], $keys);

if ($new['position'] == 'after')
$position = $position + 1;

// Create the new array in the correct format, using the slug!
$new_button = array();
$new_button[$new['slug']] = $new;

// Don't need these keys anymore.
unset($new_button[$new['slug']]['position']);
unset($new_button[$new['slug']]['parent']);
unset($new_button[$new['slug']]['slug']);

// Putting it all together now.
$buttons = array_merge(
array_slice($buttons, 0, $position),
$new_button,
array_slice($buttons, $position)
);
}

return $buttons;
}

Thanks for your help guys :)

Keep keys when shifting associative array

You can combine spliced keys and spliced values:

function custom_splice(&$ar, $a, $b){
$out = array_splice($ar, $a, 1);
array_splice($ar, $b, 0, $out);
}

function moveElement(&$array, $a, $b) {
$keys = array_keys($array);

custom_splice($array, $a, $b);
custom_splice($keys, $a, $b);

$array = array_combine($keys,$array);
}

Demo

How to add a new [key] = [value] pair after a specific Associative Key in an Assoc Array in PHP?

You'll probably need to use array_splice() to cut the array into two pieces, and then recreate the array with array_merge() - Try this nifty function I just whipped up.

Live Sample: http://codepad.org/gGm5C1od

<?php
$orig = array(
"apple" => 1,
"banana" => 3,
"orange" => 4,
);

$orig = InsertKeyValuePair($orig, "plum", 2, 1);
var_dump($orig);

function InsertKeyValuePair($arr, $key, $val, $index){
$arrayEnd = array_splice($arr, $index);
$arrayStart = array_splice($arr, 0, $index);
return (array_merge($arrayStart, array($key=>$val), $arrayEnd ));
}

?>


Related Topics



Leave a reply



Submit