Array_slice with return of sliced elements - php

I'm removing a set of elements with array slice, from e certain offset to the end.
How can I get the elements that were removed, in a different array?

You just need to use array_slice twice:
$begin = array_slice($array, 0, 5);
$end = array_slice($array, 5);
Now $begin contains the first 5 elements of $array, and $end contains the rest.

array_slice will return an array containing the elements that were removed. You can also use array_diff to find the elements that were not removed.
$original = array('1','2','3','4','5');
$sliced = array_slice($original,1); // 2, 3, 4, 5
$diff = array_diff($original,$sliced); // 1

Related

Append each item of arrays to a new array [duplicate]

This question already has an answer here:
Multi dimensional loops from 4 existing arrays [duplicate]
(1 answer)
Closed 4 months ago.
I have 4 different arrays with the same count of elements. I want to add each element of each array into a new array. For example: $id_array[0] should be added into $artikel_combined. Then $name_array[0] into $artikel_combined. And so on. Then when all 4 arrays are done with index 0, then they should start with index 1 and so on.
I tried with this code but it just combines all the arrays, but not what i want.
// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);
// This is the point where i fail, because it just combines and I'm out of ideas
$arr = array_merge($id_array, $name_array, $x_array, $y_array);
$artikel_combined = [];
// Removing new Lines from the elements
foreach ($arr as $item) {
$artikel_combined[] = trim($item);
}
if the array have always the same count of elements you can cycle through them and add them together.
like
$count = count($id_array);
$artikel_combined = [];
for($i=0;$i<$count;$i++){
$artikel_combined[$i][] = id_array[$i];
$artikel_combined[$i][] = trim(name_array[$i]);
$artikel_combined[$i][] = trim(x_array[$i]);
$artikel_combined[$i][] = trim(y_array[$i]);
}
probably not the best way to solve the problem, but it should do the job :)
Using array_merge: "Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one."
But you want to join up the same array key for every array into a new array, resulting in a multidimensional array.
You could also do so using array_map passing null as the first parameter:
// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);
$artikel_combined = array_map(null, $id_array, $name_array, $x_array, $y_array);

Shifting the items in an array by a specified value

How would you go about circularly rotating the items in an array up or down by a specified value. For example
$value = 1; // circularly rotate by 1
$array = array(1,2,3,4,5);
// Should return
array(2,3,4,5,1);
The entire array is circularly rotated anti-clockwise by 1. 1 went to the end and 2 became the leading number in the array. I cannot find a reliable way to do this.
Use a for-loop with a specification on how many items you want moved, and array_shift() to shift the array. Then add the first element to a shifted array (which essentially moves the first item to the last element)
$shift = 2; // How many times you want to move it
$output = array(1, 2, 3, 4, 5);
for ($i = 0; $i < $shift; $i++) {
array_push($output , array_shift($output));
}
print_r($output); // 3, 4, 5, 1, 2
Live demo
References
http://php.net/manual/en/function.array-shift.php
http://php.net/manual/en/function.array-push.php
You can combine the array_push function that adds a value to the end of an array and the array_shift function that removes and returns the first element of an array.
<?php
$value = 1; // circularly rotate by 1
$array = array(1,2,3,4,5);
while ($value) {
array_push($array, array_shift($array));
$value--;
}
print_r($array);
?>

What's the most efficient way to array_pop() the last n elements in an array?

What's an efficient way to pop the last n elements in an array?
Here's one:
$arr = range(1,10);
$n = 2;
$popped_array = array();
for ($i=0; $i < $n; $i++) {
$popped_array[] = array_pop($arr);
}
print_r($popped_array); // returns array(10,9);
Is there a more efficient way?
Use array_splice():
If you're trying to remove the last n elements, use the following function:
function array_pop_n(array $arr, $n) {
return array_splice($arr, 0, -$n);
}
Demo
If you want to retrieve only the last n elements, then you can use the following function:
function array_pop_n(array $arr, $n) {
array_splice($arr,0,-$n);
return $arr;
}
Demo
It's important to note, looking at the other answers, that array_slice will leave the original array alone, so it will still contain the elements at the end, and array_splice will mutate the original array, removing the elements at the beginning (though in the example given, the function creates a copy, so the original array still would contain all elements). If you want something that literally mimics array_pop (and you don't require the order to be reversed, as it is in your OP), then do the following.
$arr = range(1, 10);
$n = 2;
$popped_array = array_slice($arr, -$n);
$arr = array_slice($arr, 0, -$n);
print_r($popped_array); // returns array(9,10);
print_r($arr); // returns array(1,2,3,4,5,6,7,8);
If you require $popped_array to be reversed, array_reverse it, or just pop it like your original example, it's efficient enough as is and much more direct.
Why not use array_slice. You can give a start and a length, so if you do 2 from the end you will get the last two items in the array:
$arr = range(1,10);
$n = 2;
$start = count($arr) - $n;
print_r(array_slice($arr, $start, $n));
Thanks for the array_slice comments. I don't know why that didn't immediately come to mind.
It looks (to me) like the easiest way is:
$arr = range(1,10);
$n = 2;
$popped_array = array_slice($arr,-$n);
print_r($popped_array); // returns array(10,9);

Set array to have a maximum of 21 elements

I have an array, and I don't know how may elements there are in the array. It could be 1, it could be 500, but I need the maximum amount to elements to be 21.
I know I can check the length using count(), but how do I chop the rest off if it is too long? Thanks.
You can use SplFixedArray it a good way to manage fixed size array .....
$array = new SplFixedArray(21);
Example
$array = SplFixedArray::fromArray($array);
$array->setSize(21);
See PHP Documentation
Try this code:
if(count($array) > 21){
$subarray = array_slice($array, 0, 21);
}
Explanation:
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
If your array is $arr then:
$subArray = array_slice($arr,0,21);
You can use array_slice to chop off the exceeding portion.
if(count($array) > 21){
$array = array_slice($array, 0, 21);
}
http://php.net/manual/function.array-slice.php
you need to use array_slice by specifying the offset as 0, and length as 21.
if(count($your_array) > 21){
$new_array = array_slice($your_array, 0, 21);
}
You can use array_splice to remove the elements beyond what you need

PHP keep first 6 items in an array and drop the rest

I am wondering how I can drop any array items that come after a certain number like 6. Is there something in PHP that enables you do do it? Or is it a custom function that needs to be written
You could use array_slice for this purpose. For example:
$testArray = range(0, 10);
// Ensure there are at least six items in the source array.
if(count($testArray) >= 6) {
// Grab the first six items.
$firstSixItemsFromArray = array_slice($testArray, 0, 6);
}
If you're looking to take the first six elements of an array, based on position in the array, then array_slice or array_splice is the way to go.
array_splice($array, 6);
If you want to keep all elements with value less than 6, you could do something like:
$array = array_filter($array, function($v) { return $v <= 6; });

Categories