note 118266 added to ref.array
| From: | nicoolasens at gmail dot com | Date: | Fri, 06 Nov 2015 10:15:32 +0000 |
| Subject: | note 118266 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-204092@lists.php.net to get a copy of this message | ||
/*to change an index without rewriting the whole table and leave at the same place.
*/
<?php
function change_index(&$tableau, $old_key, $new_key) {
$changed = FALSE;
$temp = 0;
foreach ($tableau as $key => $value) {
switch ($changed) {
case FALSE :
//creates the new key and deletes the old
if ($key == $old_key) {
$tableau[$new_key] = $tableau[$old_key];
unset($tableau[$old_key]);
$changed = TRUE;
}
break;
case TRUE :
//moves following keys
if ($key != $new_key){
$temp= $tableau[$key];
unset($tableau[$key]);
$tableau[$key] = $temp;
break;
}
else {$changed = FALSE;} //stop
}
}
array_values($tableau); //free_memory
}
//Result :
$tableau = array(1, 2 , 3, 4,5, 6, 7, 8, 9, 10);
$res = print_r($tableau, TRUE);
$longueur = strlen($res) -1;
echo "Old array :\n" . substr($res, 8, $longueur) . "\n" ;
change_index ($tableau, 2, 'number 2');
$res = print_r($tableau, TRUE);
$longueur = strlen($res) -10;
echo "New array :\n" . substr($res, 8, $longueur) . "\n" ;
/*
Old array :
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
New array :
[0] => 1
[1] => 2
[numéro 2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
*/
?>
----
Server IP: 92.48.119.85
Probable Submitter: 2.3.117.88
----
Manual Page -- http://php.net/manual/en/ref.array.php
Edit -- https://master.php.net/note/edit/118266
Del: integrated -- https://master.php.net/note/delete/118266/integrated
Del: useless -- https://master.php.net/note/delete/118266/useless
Del: bad code -- https://master.php.net/note/delete/118266/bad+code
Del: spam -- https://master.php.net/note/delete/118266/spam
Del: non-english -- https://master.php.net/note/delete/118266/non-english
Del: in docs -- https://master.php.net/note/delete/118266/in+docs
Del: other reasons-- https://master.php.net/note/delete/118266
Reject -- https://master.php.net/note/reject/118266
Search -- https://master.php.net/manage/user-notes.php