توابع array_splice() در PHP

مثال

حذف عناصر از آرایه و جایگزین کردن آنها با عناصر جدید:

<?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 Instance

تعریف و نحوه استفاده

توابع 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 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, this number of elements is removed.
  • If this value is set to a negative number, 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, all elements from the start parameter to the end of the array are removed.
array

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

If there is only one element, it can be set as a string without setting it 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 Instance

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 Instance