Php remove all elements from array

array_splice

Удаляет length элементов, расположенных на расстоянии offset из массива input , и заменяет их элементами массива replacement , если он передан в качестве параметра.

Обратите внимание, что числовые ключи в массиве input не сохраняются.

Замечание: Если параметр replacement не является массивом, он будет преобразован к нему (т.е. (array) $parameter ). Это может привести к неожиданным результатам при использовании объекта или NULL в качестве replacement .

Список параметров

Если параметр offset положителен, будут удалены элементы, находящиеся на расстоянии offset от начала input . Если offset отрицателен, будут удалены элементы, находящиеся на расстоянии offset от конца input .

Если параметр length опущен, будут удалены все элементы начиная с позиции offset и до конца массива. Если length указан и он положителен, то будет удалено именно столько элементов. Если же параметр length отрицателен, то конец удаляемой части элементов будет отстоять на это количество от конца массива. Совет: для того, чтобы удалить все элементы массива, начиная с позиции offset до конца массива, в то время как указан параметр replacement , используйте count($input) в качестве параметра length .

Читайте также:  Питон классы задачи примеры

Если передан массив replacement в качестве аргумента, тогда удалённые элементы будут заменены элементами этого массива.

Если параметры offset и length таковы, что из исходного массива не будет ничего удалено, тогда элементы массива replacement будут вставлены на позицию offset . Обратите внимание, что ключи массива replacement не сохраняются.

Совет: если replacement является просто одним элементом, нет необходимости заключать его в array(), если только этот элемент сам не является массивом, объектом или NULL .

Возвращаемые значения

Возвращает массив, содержащий удалённые элементы.

Примеры

Пример #1 Примеры использования array_splice()

$input = array( «red» , «green» , «blue» , «yellow» );
array_splice ( $input , 2 );
// $input теперь array(«red», «green»)

$input = array( «red» , «green» , «blue» , «yellow» );
array_splice ( $input , 1 , — 1 );
// $input теперь array(«red», «yellow»)

$input = array( «red» , «green» , «blue» , «yellow» );
array_splice ( $input , 1 , count ( $input ), «orange» );
// $input теперь array(«red», «orange»)

$input = array( «red» , «green» , «blue» , «yellow» );
array_splice ( $input , — 1 , 1 , array( «black» , «maroon» ));
// $input теперь array(«red», «green», «blue», «black», «maroon»)

$input = array( «red» , «green» , «blue» , «yellow» );
array_splice ( $input , 3 , 0 , «purple» );
// $input теперь array(«red», «green», «blue», «purple», «yellow»);
?>

Пример #2 array_splice() examples

Следующие выражения одинаково меняют значения массива $input :

array_push ( $input , $x , $y );
array_splice ( $input , count ( $input ), 0 , array( $x , $y ));
array_pop ( $input );
array_splice ( $input , — 1 );
array_shift ( $input );
array_splice ( $input , 0 , 1 );
array_unshift ( $input , $x , $y );
array_splice ( $input , 0 , 0 , array( $x , $y ));
$input [ $x ] = $y ; // для массивов, где ключ равен смещению
array_splice ( $input , $x , 1 , $y );
?>

Смотрите также

  • array_slice() — Выбирает срез массива
  • unset() — Удаляет переменную
  • array_merge() — Сливает один или большее количество массивов

Источник

PHP array_splice() Function

Remove elements from an array and replace it with new elements:

Definition and Usage

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements.

Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).

Note: The keys in the replaced array are not preserved.

Syntax

Parameter Values

Parameter Description
array Required. Specifies an array
start Required. Numeric value. Specifies where the function will start removing elements. 0 = the first element. If this value is set to a negative number, the function will start that far from the last element. -2 means start at the second last element of the array.
length Optional. Numeric value. Specifies how many elements will be removed, and also length of the returned array. If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will remove all elements, starting from the position set by the start-parameter.
array Optional. Specifies an array with the elements that will be inserted to the original array. If it’s only one element, it can be a string, and does not have to be an array.

Technical Details

More Examples

Example 1

The same example as the example on top of the page, but the output is the returned array:

Example 2

With the length parameter set to 0:

Источник

PHP Remove Value From Array by Key, Index, Value

Remove element, value from array in PHP; In this tutorial, you will learn how to remove elements/values, array from array in PHP with example.

When working with arrays in PHP, there are several built-in functions that allow developers to manipulate the data in various ways. One common operation is to remove an element or multiple elements from an array based on a key or index value. This can be achieved using several different PHP functions, depending on the specific use case.

How to Remove elements,values, and array from array in PHP

  • Method 1: Using unset() function
  • Method 2: Using array_diff() function
  • Method 3: Using array_splice() function
  • Method 4: Using array_pop() function

Method 1: Using unset() function

The unset() function is used to remove an element from an array. The syntax for using unset() function to remove an element from an array is as follows:

Here, $array is the name of the array, and index is the index of the element you want to remove.

Let’s take an example. Suppose you have an array named $fruits that contains the following elements:

$fruits = array("apple", "banana", "orange", "kiwi", "mango");

Now, let’s say you want to remove the element “kiwi” from the array. You can do so using the following code:

After executing this code, the array $fruits will contain the following elements:

array("apple", "banana", "orange", "mango");

Let’s take another example for removing an element from a one-dimensional array by key:

To remove an element from a one-dimensional array by key, you can use the unset() function along with the array key that want to remove. Here’s an example:

$fruits = array('apple' => 1, 'banana' => 2, 'orange' => 3, 'kiwi' => 4); unset($fruits['orange']); print_r($fruits);

In this example, you have an array of fruits with each fruit assigned a numeric value. You want to remove the ‘orange’ element from the array by its key, so we use the unset() function and specify the key as the index of the element want to remove. After that, you print the remaining elements in the array using the print_r() function.

Method 2: Using array_diff() function

Another way to remove values from an array is to use the array_diff() function. This function returns an array containing all the values of the first array that are not present in any of the other arrays.

The syntax for using array_diff() function to remove values from an array is as follows:

$new_array = array_diff($array, array(value1, value2, . ));

Here, $array is the name of the array, and value1 , value2 , etc. are the values you want to remove.

Let’s take an example. Suppose you have an array named $numbers that contains the following elements:

Now, let’s say you want to remove the values 2 and 4 from the array. You can do so using the following code:

$new_array = array_diff($numbers, array(2, 4));

After executing this code, the array $new_array will contain the following elements:

Method 3: Using array_splice() function

The array_splice() function is used to remove a portion of an array and replace it with something else. The syntax for using array_splice() function to remove values from an array is as follows:

array_splice($array, $start, $length);

Here, $array is the name of the array, $start is the index of the element where the removal should start, and $length is the number of elements to remove.

Let’s take an example. Suppose you have an array named $colors that contains the following elements:

$colors = array("red", "green", "blue", "yellow", "pink");

Now, let’s say you want to remove the elements “blue” and “yellow” from the array. You can do so using the following code:

After executing this code, the array $colors will contain the following elements:

Method 4: Using array_pop() function

The array_pop() function is a part of PHP’s array manipulation functions. It removes the last element of an array and returns it. This function modifies the original array and reduces its length by one. If the array is empty, array_pop() returns NULL.

To remove multiple elements from an array, you can call array_pop() multiple times. However, you need to be careful not to call array_pop() more times than the number of elements in the array, as it will result in an error.

Now, let’s look at some examples of using array_pop() to remove values from an array.

Example 1: Removing the last element from an array

Suppose you have an array of fruits, and you want to remove the last fruit from it. You can use the array_pop() function as follows:

$fruits = array('apple', 'banana', 'orange', 'kiwi'); $last_fruit = array_pop($fruits); echo "Removed fruit: " . $last_fruit . "
"; print_r($fruits);

In this example, the array_pop() function removes the last element, which is ‘kiwi’, and returns it. You store the removed value in $last_fruit and display it on the screen. Finally, you print the modified array using the print_r() function, which displays the remaining elements in the array.

Example 2: Removing multiple elements from an array

Suppose you have an array of numbers, and want to remove the last two elements from it. You can use the array_pop() function twice, as follows:

$numbers = array(10, 20, 30, 40, 50); array_pop($numbers); array_pop($numbers); print_r($numbers);

In this example, you call the array_pop() function twice, which removes the last two elements from the array. Finally, you print the modified array using the print_r() function, which displays the remaining elements in the array.

Conclusion

In summary, removing elements from arrays is a common task in PHP programming. Developers can use built-in functions such as array_pop(), array_shift(), and unset() to remove elements from regular arrays, and array_splice() and array_filter() for multi-dimensional arrays. By understanding how to remove elements from arrays, developers can efficiently manipulate data and build robust PHP applications.

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Источник

Оцените статью