PHP Array – Insert item before/after array index
<?php
class Arr
{
/**
* Inserts values before specific key.
*
* @param array $array
* @param sting/integer $position
* @param array $values
* @throws Exception
*/
public static function insert_before(array &$array, $position, array $values)
{
// enforce existing position
if (!isset($array[$position]))
{
throw new Exception(strtr('Array position does not exist (:1)', [':1' => $position]));
}
// offset
$offset = -1;
// loop through array
foreach ($array as $key => $value)
{
// increase offset
++$offset;
// break if key has been found
if ($key == $position)
{
break;
}
}
$array = array_slice($array, 0, $offset, TRUE) + $values + array_slice($array, $offset, NULL, TRUE);
return $array;
}
/**
* Inserts values after specific key.
*
* @param array $array
* @param sting/integer $position
* @param array $values
* @throws Exception
*/
public static function insert_after(array &$array, $position, array $values)
{
// enforce existing position
if (!isset($array[$position]))
{
throw new Exception(strtr('Array position does not exist (:1)', [':1' => $position]));
}
// offset
$offset = 0;
// loop through array
foreach ($array as $key => $value)
{
// increase offset
++$offset;
// break if key has been found
if ($key == $position)
{
break;
}
}
$array = array_slice($array, 0, $offset, TRUE) + $values + array_slice($array, $offset, NULL, TRUE);
return $array;
}
}
// test array
$array_one = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
'key4' => 'value4',
'key5' => 'value5'
);
// try to insert value before
try
{
Arr::insert_before($array_one, 'key2', array('new_key1' => 'new_value1'));
}
catch (Exception $e)
{
echo strtr('Exception: Array could not be added before :1', array(':1' => 'key2')) . PHP_EOL;
}
// try to insert value after
try
{
Arr::insert_after($array_one, 'key4', array('new_key2' => 'new_value2'));
}
catch (Exception $e)
{
echo strtr('Exception: Array could not be added after :1', array(':1' => 'key4')) . PHP_EOL;
}
// print array
var_dump($array_one);
?>
0 comments:
Post a Comment