Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to delete all array elements after an index [duplicate]

Is it possible to delete all array elements after an index?

$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);

now some "magic"

$myArray = delIndex(30, $myArrayInit);

to get

$myArray = array(1=>red, 30=>orange); 

due to the keys in $myArray are not successive, I don't see a chance for array_slice()

Please note : Keys have to be preserved! + I do only know the Offset Key!!

like image 330
Viktor Avatar asked Feb 18 '14 10:02

Viktor


People also ask

How do you clear an array in PHP?

Basic example of empty array:$emptyArray = ( array ) null; var_dump( $emptyArray );

Does PHP have flip function?

PHP | array_flip() FunctionThis built-in function of PHP is used to exchange elements within an array, i.e., exchange all keys with their associated values in an array and vice-versa. We must remember that the values of the array need to be valid keys, i.e. they need to be either integer or string.

How do you remove an element from an array index?

You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.

What is use of Array_unique in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.


2 Answers

Without making use of loops.

<?php
    $myArrayInit = [1 => 'red', 30 => 'orange', 25 => 'velvet', 45 => 'pink']; //<-- Your actual array
    $offsetKey = 25; //<--- The offset you need to grab

    //Lets do the code....
    $n = array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
    $count = array_search($offsetKey, $n); //<--- Returns the position of the offset from this array using search
    $new_arr = array_slice($myArrayInit, 0, $count + 1, true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
    print_r($new_arr);

Output :

Array
(
    [1] => red
    [30] => orange
    [25] => velvet
)
like image 64
Shankar Narayana Damodaran Avatar answered Oct 19 '22 17:10

Shankar Narayana Damodaran


Try

$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);

See demo

like image 31
Nouphal.M Avatar answered Oct 19 '22 16:10

Nouphal.M