I have an array like this,
$ptJson = {
["phoneSMS1"]=> "mobile",
["phoneSMS2"]=> "mobile",
["phoneSMS3"]=> "mobile",
["phoneSMS4"]=> "mobile",
["phoneSMS5"]=> "main"
}
And I have to delete the phoneSMS3
, so I used unset
to unset the key
unset($ptJson['phoneSMS3']);
It worked great.! Now I want to move rest keys level-up by one, but don't know how. Searched but have no luck.
So, how to find the rest array keys after phoneSMS3
?
I'd iterate over the keys from the position you want to remove till the end of the array and assign the following key to the current position in each iteration:
$prefix = 'phoneSMS';
$index = 3;
while (array_key_exists($prefix . ($index + 1), $ptJson)) {
$ptJson[$prefix . $index] = $ptJson[$prefix . ($index + 1)];
++$index;
}
unset($ptJson[$prefix . $index]);
I think reset($array) function may help.
for($i = 2; $i < count($ptJson); $i++){
$ptJson[$i] = 'phoneSMS'.($i+1);
}
this is how you can acess it you just should use it a bit more generic
$flg=0;
$i=1;
foreach($ptJson as $key=>$val){
$i++;
if($key =="phoneSMS3"){
unlink($ptJson[$key]);
$flg=1;
}
if($flg==1)
$ptJson[$key]=$ptJson["phoneSMS".$i];
}