PHP array_splice() συνάρτηση

Παράδειγμα

Αφαίρεση στοιχείων από τη μάζα και αντικατάσταση τους με νέα στοιχεία:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>

Run Instances

Ορισμός και χρήση

Η συνάρτηση array_splice() αφαιρεί επιλεγμένα στοιχεία από τη μάζα και τα αντικαθιστά με νέα στοιχεία. Η συνάρτηση αυτή θα επιστρέψει επίσης τη μάζα που περιέχει τα αφαιρεμένα στοιχεία.

Συμβουλή:Αν η συνάρτηση δεν αφαιρεί κανένα στοιχείο (length=0), θα αφαιρεθεί από start Τοποθετείται η αντικατασταμένη μάζα στη θέση των παραμέτρων (βλέπε παράδειγμα 2).

Σημείωση:Δεν διατηρείται το όνομα κλειδιού του αντικατασταμένου μάζας.

Περιγραφή

Η συνάρτηση array_splice() είναι παρόμοια με array_slice() Η συνάρτηση είναι παρόμοια, επιλέγει μια σειρά στοιχείων από τη μάζα, αλλά δεν τα επιστρέφει,而是 τα αφαιρεί και τα αντικαθιστά με άλλες τιμές.

Αν παρέχεται ο τέταρτος παράμετρος, τα προηγούμενα επιλεγμένα στοιχεία θα αντικατασταθούν από το μάζα που καθορίζει ο τέταρτος παράμετρος.

Το τελικό μάζα θα επιστρέψει.

Γλώσσα

array_splice(array,start,length,array)
Παράμετροι Περιγραφή
array Απαιτείται. Καθορίζει τη μάζα.
start

Απαιτείται. Αριθμητικός. Καθορίζει τη θέση ξεκινήματος για την αφαίρεση στοιχείων.

  • 0 = ο πρώτος στοιχείο.
  • Αν ο τιμή είναι θετική, θα αφαιρεθούν τα στοιχεία από την καθορισμένη απόκλιση στη μάζα.
  • Αν ο τιμή είναι αρνητική, θα αφαιρεθούν τα στοιχεία από το τέλος της μάζας με βάση την καθορισμένη απόκλιση.
  • -2 means starting from the second-to-last element of the array.
length

Optional. Numeric. Specifies the number of elements to be removed, which is also the length of the returned array.

  • If this value is set to a positive number, then the specified number of elements are removed.
  • If this value is set to a negative number, then all elements from the start to the end of the array minus the length of the last length are removed.
  • If this value is not set, then all elements from the start parameter setting position to the end of the array are removed.
array

Optional. Specifies an array that contains elements to be inserted into the original array.

If only one element is present, it can be set as a string without being set as an array.

Technical Details

Return Value: Returns an array consisting of the extracted elements.
PHP Version: 4+

More Examples

Example 1

As with the example in the previous part of this page, but the output returns the array:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
print_r(array_splice($a1,0,2,$a2));
?>

Run Instances

Example 2

Set the length parameter to 0:

<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>

Run Instances