หากต้องการสร้างดัชนีอาร์เรย์ใหม่ใน PHP โค้ดจะเป็นดังนี้ -
ตัวอย่าง
<?php $arr = array( 0=>"150", 1=>"100", 2=>"120", 3=>"110", 4=>"115" ); echo "Array...\n"; foreach( $arr as $key => $value) { echo " Key = " . $key . ", Value = " . $value . "\n"; } $arr = array_combine(range(2, count($arr) + (1)), array_values($arr)); echo "\nArray after re-indexing\n"; foreach( $arr as $key => $value) { echo " Key = " . $key . ", Value = " . $value . "\n"; } ?>
ผลลัพธ์
สิ่งนี้จะทำให้เกิดผลลัพธ์ดังต่อไปนี้−
Array... Key = 0, Value = 150 Key = 1, Value = 100 Key = 2, Value = 120 Key = 3, Value = 110 Key = 4, Value = 115 Array after re-indexing Key = 2, Value = 150 Key = 3, Value = 100 Key = 4, Value = 120 Key = 5, Value = 110 Key = 6, Value = 115
ตัวอย่าง
เรามาดูตัวอย่างอื่นกัน −
<?php $arr = array( "a"=>"150", "b"=>"100", "c"=>"120", "d" =>"110", "e"=>"115" ); echo "Array...\n"; foreach( $arr as $key => $value) { echo " Key = " . $key . ", Value = " . $value . "\n"; } $arr = array_combine(range("b", chr(count($arr) + (ord("b")-1))), array_values($arr)); echo "\nArray after re-indexing\n"; foreach( $arr as $key => $value) { echo " Key = " . $key . ", Value = " . $value . "\n"; } ?>
ผลลัพธ์
สิ่งนี้จะทำให้เกิดผลลัพธ์ดังต่อไปนี้−
Array... Key = a, Value = 150 Key = b, Value = 100 Key = c, Value = 120 Key = d, Value = 110 Key = e, Value = 115 Array after re-indexing Key = b, Value = 150 Key = c, Value = 100 Key = d, Value = 120 Key = e, Value = 110 Key = f, Value = 115