Suppose I have this array:
$array = array('10', '20', '30.30', '40', '50');
Questions:
What is the fastest/easiest way to remove the first item from the above array?
What is the fastest/easiest way to remove the last item from the above array?
So the resulting array contains only these values:
'20'
'30.30'
'40'
Using array_slice is simplest
$newarray = array_slice($array, 1, -1);
If the input array has less than 3 elements in it, the output array will be empty.
To remove the first element, use array_shift, to remove last element, use array_pop:
<?php
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);
array_pop($array); // remove the last element
array_shift($array); // remove the first element
array_slice is going to be the fastest since it's a single function call.
You use it like this:
array_slice($input, 1, -1);
Make sure that the array has at least 2 items in it before doing this, though.
Check this code:
$arry = array('10', '20', '30.30', '40', '50');
$fruit = array_shift($arry);
$fruit = array_pop($arry);
print_r($arry);
Removes the first element from the array, and returns it:
array_shift($array);
Removes the last element from the array, and returns it:
array_pop($array);
If you dont mind doing them both at the same time, you can use:
array_shift($array,1,-1));
to knock off the first and last element at the same time.
Check the array_push, array_pop and array_slice documentation :)
<?php
$array = array("khan","jan","ban","man","le");
$sizeof_array = sizeof($array);
$last_itme = $sizeof_array-1;
//$slicearray= array_slice($array,'-'.$sizeof_array,4);// THIS WILL REMOVE LAST ITME OF ARRAY
$slicearray = array_slice($array,'-'.$last_itme);//THIS WILL REMOVE FIRST ITEM OF ARRAY
foreach($slicearray as $key=>$value)
{
echo $value;
echo "<br>";
}
?>
Related
is it possible that, get arrays to $value with key:
Example:
$array = Array("one"=>Array("field1"=>"value1","field2"=>"value2"),
"two"=>Array("field3"=>"value3","field4"=>"value4"));
Export arrays to value:
$first = any_main_php_function_name(0,$array);
$second = any_main_php_function_name(1,$array);
Result:
$first = Array("field1"=>"value1","field2"=>"value2");
$second = Array("field3"=>"value3","field4"=>"value4");
Basically, I wanna extract multiple array. If there is no such function (any_main_php_function_name) in PHP so How can i extract above $array.
You don't need any funtion to do that. Simply get subarrays like this:
$first = $array['one'];
$second = $array['two'];
Unless you don't know the one,two keys, then you can use array_shift to get first item (one subarray). Remember that this functions also removes returned value from root array.
array_slice does what you want
$first = array_slice($array, 0, 1);
$second = array_slice($array, 1, 1);
print_r($first);
print_r($second);
May be you can array_shift to get the element from array, Like this:
$first_element=array_shift($array);
Make sure it only removes the first element from the array and
return the value of removed element.
And if you don't want to remove the element or get the sub-array in any sequence, then you can create a function like this,
function myFunction($index,$array) {
$keys = array_keys($array);
$sub_array=$arr[$keys[$index]];
}
In above function we just get the keys in a array and then use the known index to get the sub-array using keys array.
Please check this
foreach($array["one"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}
foreach($array["true"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}
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.
If I have the following array. What would be the best way to add a element to list[] for the last element of $myArray[]? Note that list[] has numerical indexes (i.e. not associative). Thanks!
$myArray[] = array( 'name' => 'hello', 'list' => array() );
If $myArray is not associative
array_push($myArray[count($myArray)-1]['list'], 'new element');
or
$myArray[count($myArray)-1]['list'][] = 'new element';
with this method you change the position of the array pointer.
You can do it like this:
$last = array_pop($myArray); // remove last element of array
$last['list'][] = "new element"; // add element to array
$myArray[] = $last; // add changed last element again
$myArray[count($myArray)-1]['list'][]="something to go in 'list' array";//this shall append
//to the second dimension array with keyname 'list'
There is actually a more beautiful way (in my opinion):
$ref = &$myArray[];
$ref['list'][] = 'new item'
As you can see $ref - is reference to the last element of $myArray, so you can change the last element by changing $ref;
array_push function do that.
array_push()
All I need to two is remove the final two elements from an array, which only contains 3 elements, output those two removed elements and then output the non-removed element. I'm having trouble removing the two elements, as well as keeping their keys.
My code is here http://pastebin.com/baV4fMxs
It is currently outputting : Java
Perl
Array
I want it to output:
[One] => Perl and [Two] => Java
[Zero] => PHP
$last=array_splice($inputarray,-1);
//$last has now key=>value of last element
$middle=array_splice($inputarray,-1);
//$middle has now key=>value of middle element
//$inputarray has now only key=>value of first element
It seems to me that you want to retrieve those two values being removed before getting rid of them. With this in mind, I suggest the use of array_pop() which simultaneously returns the last item in the array and removes it from the array.
$val = array_pop($my_array);
echo $val; // Last value
$val = array_pop($my_array);
echo $val; // Middle value
// Now, $my_array has only the first value
You mentioned keys, so I assume it's an associative array. In order to remove an element, you can call the unset function, like this:
unset ($my_array['my_key'])
Do this for both elements that you want to remove.
array_pop will do it for you quite easily:
$array = array( 'one', 'two', 'three');
$last = array_pop( $array); echo $last . "\n";
$second = array_pop( $array); echo $second . "\n";
echo $array[0];
Output:
three
two
one
Demo
What is the fastest and easiest way to get the last item of an array whether be indexed array , associative array or multi-dimensional array?
$myArray = array( 5, 4, 3, 2, 1 );
echo end($myArray);
prints "1"
array_pop()
It removes the element from the end of the array. If you need to keep the array in tact, you could use this and then append the value back to the end of the array. $array[] = $popped_val
try this:
$arrayname[count(arrayname)-1]
I would say array_pop In the documentation: array_pop
array_pop — Pop the element off the end of array
Lots of great answers. Consider writing a function if you're doing this more than once:
function array_top(&$array) {
$top = end($array);
reset($array); // Optional
return $top;
}
Alternatively, depending on your temper:
function array_top(&$array) {
$top = array_pop($array);
$array[] = $top; // Push top item back on top
return $top;
}
($array[] = ... is preferred to array_push(), cf. the docs.)
For an associative array:
$a= array('hi'=> 'there', 'ok'=> 'then');
list($k, $v) = array(end(array_keys($a)), end($a));
var_dump($k);
var_dump($v);
Edit: should also work for numeric index arrays