Improve the insertAt function in the following PHP code to insert data anywhere in the array $ items

Source: Internet
Author: User
& Amp; lt ;? Php $ items [& #039; apple & #039;, & #039; Orange & #039;, & #039; Li & #039;, & #039; pineapple & #039;, & #039; banana & #039;, & #039; dragon fruit & #039;]; * $ array passed in by items $ position of index to be inserted $ value data to be inserted * functioninsertAt ($ items, $ index, $ value) {code ...}} $ itemsinsertA...

$ Items = ['apple', 'orange', 'pe', 'pineapple ', 'Banana', 'Dragon go'];

/*
$ Array imported by items
$ Index location to be inserted
$ Value: the data to be inserted.
*/
Function insertAt ($ items, $ index, $ value ){

return $items;

}

$ Items = insertAt ($ items, 2, 'orange'); // after the execution is complete, the result is as follows:
['Apple', 'orange', 'orange', 'pear ', 'pineapple', 'Banana ', 'Dragon go'];

Reply content:

$ Items = ['apple', 'orange', 'pe', 'pineapple ', 'Banana', 'Dragon go'];

/*
$ Array imported by items
$ Index location to be inserted
$ Value: the data to be inserted.
*/
Function insertAt ($ items, $ index, $ value ){

return $items;

}

$ Items = insertAt ($ items, 2, 'orange'); // after the execution is complete, the result is as follows:
['Apple', 'orange', 'orange', 'pear ', 'pineapple', 'Banana ', 'Dragon go'];

php
  String 'apple' (length = 6) 1 => string 'orange' (length = 6) 2 => string 'orange' (length = 6) 3 => string 'pe' (length = 3) 4 => string 'pineapple '(length = 6) 5 => string 'banana' (length = 6) 6 => string 'Dragon go' (length = 9 )*/

@ Song XiaoBei refers to the native Implementation of array_splice in php. We must never duplicate the wheel.

Create one here for fun.

function insertAt($items, $value, $index=0) {    is_numeric($index) and    $items[($index-'0.1').'x'] = $value and    ksort($items);    return array_values($items);}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.