Deleting from PHP array and having indexes adjusted - php

If I have this array:
<?php
$array[0]='foo';
$array[1]='bar';
$array[2]='foo2';
$array[3]='bar3';
?>
And I want to delete the second entry ($array[1]), but so that all the remaining entries' indexes automatically get adjusted, so the next 2 elements whose indexes are 2 and 3, become 1 and 2.
How can this be done, or is there any built in function for this?

There are several ways to do that. One is to use array_values after deleting the item to get just the values:
unset($array[1]);
$array = array_values($array);
var_dump($array);
Another is to use array_splice:
array_splice($array, 1, 1);
var_dump($array);

You can use array_splice(). Note that this modifies the passed array rather than returning a changed copy. For example:
$array[0] = 'foo';
//etc.
array_splice($array, 1, 1);
print_r($array);

I always use array_merge with a single array
$array = array_merge($array);
print_r($array);
from php.net:
http://us.php.net/array_merge
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

Related

array_shift and print_r behaving wierd in PHP

I wanted to test array_shift on a simple example:
$a = ['a', 'b', 'c', 'd'];
$rem = array_shift($a);
print_r($rem);
Which only returns me: a, instead of an array of: ['b', 'c', 'd'].
php.net docs on array_shift state the following:
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be affected.
This function is supposed to remove the first element and return all the rest with re-ordered keys.
Now, I copied the example from the docs site as is (tried with both [] and array()):
$stack = ["orange", "banana", "apple", "raspberry"];
$fruit = array_shift($stack);
print_r($stack);
Now this returns as expected:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
I don't understand what just happend here or what I did wrong.
My example only differs in variable names and elements in the array.
And I hardly don't believe the issue would be because of my usage of single-quotes '.
Also, here is a demo on Sandbox.
array_shift() is a stand-alone function - you don't need to assign it to a value, it automatically unsets it from the given variable:
<?php
$a = ['a', 'b', 'c', 'd'];
array_shift($a);
print_r($a);
https://3v4l.org/GEr3g
array_shift() shifts the first value of the array off and returns it
The "it" refers to "the first value", not to "the array". It shifts off the first value and returns said first value; the array is being shortened by that process. Pay close attention to what is being returned in the example code ($fruit) and what you print ($stack).
To leave the original array intact and return a new, shorter array, you'd do:
$rem = array_slice($a, 1);
In you example $rem is the return from the function array_shift as stated on the doc it will return the eliminated index value, on the other side whenever you print
print_r($a);
This will return the array after the function performed.
As the php doc array_shift shows.
The return result of array_shift is the first value of the array that been shifted off, and remove the first value of the original array.
array_shift ( array &$array ) : mixed
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be affected.

Remove all elements before x from an array php

if I give you:
$array = array(object1, object2, object3, object4);
and say, at position 2, remove all elements before this position so the end result is:
$array = array(object3, object4);
What would I do? I was looking at array_shift and array_splice to achieve what I wanted - how ever I am not sure which to use or how to use them to achieve the desired affect.
Use array_slice. For more detail check link http://php.net/manual/en/function.array-slice.php
$array = array(object1, object2, object3, object4);
$array = array_slice($array,2); // 2 is position
Or if you are looking into the values instead of the index, with a tiny adjustment in #Ashwani's answer you can have:
$array = array('object1', 'object2', 'object3', 'object4');
$slice = array_slice($array, array_search('object3',$array));
array_slice is one way to go about it, however, if you are wanting to remove all the elements in an any array before a specific value, without searching, then:
//assuming you've already verified the match is in the array
//make a copy of $array first if you don't want to break the original
while($array[0] !== $match) {
array_shift(&$array);
}
Alternatively, you could:
$index = array_search($match, array_values($array));
if($index !== false) $array = array_slice($array, $index);
This accomplished both the verification and slice. Note the array_values() is used to account for associative arrays.

Put multiple PHP arrays inside another array maintaining keys including duplicates

If I have two arrays and I want to "combine" them into one array whilst maintaining each individual array and leaving the keys as they are as they are always duplicated each iteration, can I do this?:
$array1 = array('0'=>'Bob', '1'=>'Tom', '2'=>'John');
$array2 = array('0'=>'Michelle', '1'=>'Joan', '2'=>'Susan');
If I use array_merge:
$new_array = array_merge($array1, $array2);
I get:
array('0'=>'Bob','1'=>'Tom','2'=>'John','3'=>'Michelle','4'=>'Joan','5'=>'Susan')
whereas I want to get something like:
array(array('0'=>'Bob', '1'=>'Tom', '2'=>'John'),array('0'=>'Michelle', '1'=>'Joan', '2'=>'Susan'))
Create a new array and add the other arrays to that one like this:
$arr = array($array1, $array2);
$ new_array = array ($ array, $ array2);

How to get the last n items in a PHP array as another array?

How to I get an array of the last n items of another array in PHP?
$n is equal to the number of items you want off the end.
$arr = array_slice($old_arr, -$n);
You can use array_slice:
$arr = array_slice($old_arr, -$n, $n, true);
If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag (4th parameter) set to true to avoid this.

iterate through range of numbers to add as keys

I have a range of 67 numbers, something like 256 through to 323, which I want to add to an existing array. it doesn't matter what the values are.
looking for code to iterate through those numbers to add them as keys to the array without adding each one at a time
Try array_fill_keys and range
$existingArray = array('foo', 'bar', 'baz');
$existingArray += array_fill_keys(range(256,323), null);
Use whatever you like instead of null. You could also use array_flip() instead of array_fill_keys(). You'd get the index keys as values then, e.g. 256 => 1, 257 => 2, etc.
Alternatively, use array_merge instead of the + operator. Depends on the outcome you want.
you can use range() eg range(256,323)
push(); could be a look worth, or you can do it
like this
for($i=0;$i<count($array);$i++)
{
$anotherArray[$i] = $array[$i];
}
You can try using the range and array_merge functions.
Something like:
<?php
$arr = array(1,2,3); // existing array.
$new_ele = range(256,323);
// add the new elements to the array.
$arr= array_merge($arr,$new_ele);
var_dump($arr);
?>

Categories