3

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?

4
  • Do you mean you want to change the key phoneSMS4 to phoneSMS3, phoneSMS5 to phoneSMS5, etc? Commented Oct 18, 2016 at 12:16
  • Yes exactly want to do that. @Mureinik Commented Oct 18, 2016 at 12:24
  • That isn't php array. Php array hasn't {}. Commented Oct 18, 2016 at 12:27
  • Taken from fire-bug. So please forgive me for that. @Mohammad Commented Oct 18, 2016 at 12:28

4 Answers 4

2
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

Sign up to request clarification or add additional context in comments.

Comments

1

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]);

Comments

1
$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];
}

1 Comment

I want to get the rest array keys after phoneSMS3. You sure this will give me that?
-1

I think reset($array) function may help.

2 Comments

Can you please give an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.