PHP

Buy me a beer or a book?

amazon PayPal - The safer, easier way to donate online!

PHP strip individual keys and shunt array

As mentioned at the end of January I had come across the problem where its very difficult to find a function online which basically loops through an array and removes the specficied key, but also shunts down the rest of the array so there isn't empty keys leftover.

Anyway, here is the code all noted out to remove items from an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

 
//----------------------------------------------------------
//
// Syntax: $myNewArray = remKey($myOldArray, 4)
// [This will remove the 4th attribute from the array]
//
//-----------------------------------------------------------
 
function remKey($arr, $key)
{
$i = 0;
$ii = 1;
$found = false;
 
//Loops through all the existing array keys
while (isset($arr[$i]))
{
//checks if the key matchs the one to be remove
//or if that key has been found
if ($i == $key || $found == true)
{
//overwrite the current key with the previous
$arr[$i] = $arr[$ii];
//specifies the key has been found and overwritten
$found = true;
}
//if the key hasn't been found the array
//just repopulates itself
else
{
$arr[$i] = $arr[$i];
}
$i++;
$ii++;
}
//counts the amount of keys in the array, then deducts one
$c = count($arr);
$c--;
//removes the last key completely so the array has the specified
//one overwritten, and the last one is now a duplicate of the
//second from last array key.
unset($arr[$c]);
 
return $arr;
}
?>

Free Downloads