Refine the InsertAt function in the following PHP code to insert data anywhere in the array $items

Source: Internet
Author: User
Tags pear pears

$items = [' Apple ', ' orange ', ' pear ', ' pineapple ', ' banana ', ' dragon Fruit '];

/*
$items the incoming array
$index the location to insert
$value the data to be inserted
*/
function InsertAt ($items, $index, $value) {

return $items;

}

$items =insertat ($items, 2, ' oranges '); When the execution is complete, the results are as follows
[' Apples ', ' oranges ', ' oranges ', ' pears ', ' pineapple ', ' Bananas ', ' dragon Fruit '];

Reply content:

$items = [' Apple ', ' orange ', ' pear ', ' pineapple ', ' banana ', ' dragon Fruit '];

/*
$items the incoming array
$index the location to insert
$value the data to be inserted
*/
function InsertAt ($items, $index, $value) {

return $items;

}

$items =insertat ($items, 2, ' oranges '); When the execution is complete, the results are as follows
[' Apples ', ' oranges ', ' oranges ', ' pears ', ' pineapple ', ' Bananas ', ' dragon Fruit '];

php
  
    string '苹果' (length=6)  1 => string '橘子' (length=6)  2 => string '橙子' (length=6)  3 => string '梨' (length=3)  4 => string '菠萝' (length=6)  5 => string '香蕉' (length=6)  6 => string '火龙果' (length=9) */

The Array_splice mentioned in song Xiao Bei is a native implementation of PHP. We must not make the wheel again.

Build one here, just 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.