Remove element and reindex - php

the logic is to get last element from the elemnt after particular interval when all the elemnts are been removed. suppose there are five users and every secound user is been eliminated , then i have to find the last remaining user.
$foo = array(
'0'=>'1',
'1'=>'2',
'2'=>'3',
'3'=>'4',
'4'=>'5',
'5'=>'6'
);
now remove element indexed at 2 and reindex the array in below format.
$foo = array(
'0'=>'4',
'1'=>'5',
'2'=>'6',
'3'=>'1',
'4'=>'2',
);

You can use unset(), but you'll also need to call array_values() to force a re-index. For example:
unset($foo[2]);
$foo = array_values($foo);

The original question is a bit unclear. I understand you want to remove index X, and place all items after index X as first items in the array.
$index2remove = 2;
$newArray1 = array_slice($foo, $index2remove+1); // Get items after the selected index
$newArray2 = array_slice($foo, 0, $index2remove); // get everything before the selected index
$newArray = array_merge($newArray1, $newArray2); // and combine them
Or shorter and a bit less memory consuming (but harder to read):
$index2remove = 2;
$newArray = array_merge(
array_slice($foo, $index2remove+1), // add last items first
array_slice($foo, 0, $index2remove) // add first items last
);
You do NOT need to unset value 2 in my code, you simple slice it out. We do that with the -1 in the 2nd splice function.
If you want, you can replace $newArray = array_merge() with $foo = array_merge(), but ONLY in the second, if you dont need to save the original array.
Edit: Changed small error, thank you plain jane

Try this of which the output is given below
$foo = array('0'=>'1','1'=>'2','2'=>'3','3'=>'4','4'=>'5','5'=>'6');
//need to input this as the index of the element to be removed
$remove_index = "2";
unset($foo[$remove_index]);
$slice1 = array_slice($foo, 0, $remove_index);
$slice2 = array_slice($foo, $remove_index);
$final_output = array_merge($slice2, $slice1);
Output
Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 1
[4] => 2
)

Related

How to set last index key

I would like to find out how I can set the last index key (without knowing what it is in advance) in the following code that fetches a price from a SIMPLEXML response:
$product_price = $CATEGORIES->PRODUCTS->PRICES->PRICE[0]->AMOUNT;
There may be more than 1 price, so at times there are 3, at times 5 etc. But I would only like to get the last one, so the key in PRICE[0] needs to dynamically fetch the last one.
How can this be achieved?
Thanks.
You can you use end() to get last element in array.
$prices = $CATEGORIES->PRODUCTS->PRICES;
$last_price = end($prices);
$amount = $last_price->AMOUNT;
You can use array_pop()
Like this:
$array = array('a','b','c');
// This get the value and remove it from the end of the array
$test1 = array_pop($array);
// This will only get the value from the array
$array[] = $test2 = array_pop($array);
var_dump($test1); // "c"
var_dump($test2); // "b"
var_dump($array); // array('a', 'b')

Swap my element's order to be the first in an array

Let's say I have an array like so:
array(
[0]=>1
[1]=>3
[3]=>5
[15]=>6
);
Arbitrarily I want array[15] to be the first:
array(
[15]=>6
[0]=>1
[1]=>3
[3]=>5
);
What is the fastest and most painless way to do this?
Here are the things I've tried:
array_unshift - Unfortunately, my keys are numeric and I need to keep the order (sort of like uasort) this messes up the keys.
uasort - seems too much overhead - the reason I want to make my element the first in my array is to specifically avoid uasort! (Swapping elements on the fly instead of sorting when I need them)
Assuming you know the key of the element you want to shift, and that element could be in any position in the array (not necessarily the last element):
$shift_key = 15;
$shift = array($shift_key => $arr[$shift_key]);
$arr = $shift + $arr;
See demo
Updated - unset() not necessary. Pointed out by #FuzzyTree
You can try this using a slice and a union operator:
// get last element (preserving keys)
$last = array_slice($array, -1, 1, true);
// put it back with union operator
$array = $last + $array;
Update: as mentioned below, this answer takes the last key and puts it at the front. If you want to arbitrarily move any element to the front:
$array = array($your_desired_key => $array[$your_desired_key]) + $array;
Union operators take from the right and add to the left (so the original value gets overwritten).
If #15 is always last you can do
$last = array_pop($array); //remove from end
array_unshift($last); //push on front
To reorder the keys for sorting simply add
$array = array_values($array); //reindex array
#Edit - if we don't assume its always last then I would go with ( if we always know wwhat the key is, then most likely we will know its position or it's not a numerically indexed array but an associative one with numeric keys, as op did state "arbitrarily" so one has to assume the structure of the array is known before hand. )
I also dont see the need to reindex them as the op stated that it was to avoid sorting. So why would you then sort?
$item = $array[15];
unset($array[15]); //....etc.

create another multi dimensional array from an array

Suppose i have an array
$x= ('A'=>31, 'B'=>12, 'C'=>13, 'D'=>25, 'E'=>18, 'F'=>10);
I need to generate an array somewhat like this
$newx = (0 => array('A'=>31 , 'B' =>1) , 1 => array('B'=>11 , 'C' =>13 , 'D'=>8) , 2 =>array('D'=>17 , 'E'=>15) , 3=>array('E'=>3,'F'=>10);
Now in this case each value of $newx has to be = 32 and this is how it will work $x[A] = 31 , $x[B] = 12 so first of all we have to make the sum quantity to be 32 keeping the index same for the new array i.e
array(0=>array('A'=>31,'B'=>1) , 1=>array('B'=>11) )
the process should continue for each value of $x.
while I'm pretty sure this is a homework assignment and well, you really should provide code of your own, at least try to, I found the thing amusing so I went ahead and gave it a try. I guess I'll be downvoted for his and I probably do deserve it, but here goes anyway.
What you need to do is:
loop through your array,
determine the elements that give you 32 and then store that result in the final array.
subtract the value of the last element from your result from the corresponding element of your working array
shrink your array next by deleting the first elements until the very first element of the array you're still working with equals the last element your last result returned.
if your last result < 32, quit.
With this in mind, please try to find a solution yourself first and don't just copy-paste the code? :)
<?php
$x = array('A'=>31, 'B'=>12, 'C'=>13, 'D'=>25, 'E'=>18, 'F'=>10);
$result = array();
function calc($toWalk){
// walk through the array until we have gathered enough for 32, return result as an array
$result = array();
foreach($toWalk as $key => $value){
$count = array_sum($result);
if($count >= 32){
// if we have more than 32, subtract the overage from the last array element
$last = array_pop(array_keys($result));
$result[$last] -= ($count - 32);
return $result;
}
$result[$key] = $value;
}
return $result;
}
// logic match first element
$last = 'A';
// loop for as long as we have an array
while(count($x) > 0){
/*
we make sure that the first element matches the last element of the previously found array
so that if the last one went from A -> C we start at C and not at B
*/
$keys = array_keys($x);
if($last == $keys[0]){
// get the sub-array
$partial = calc($x);
// determine the last key used, it's our new starting point
$last = array_pop(array_keys($partial));
$result[] = $partial;
//subtract last (partial) value used from corresponding key in working array
$x[$last] -= $partial[$last];
if(array_sum($partial) < 32) break;
}
/*
reduce the array in size by 1, dropping the first element
should our resulting first element not match the previously returned
$last element then the logic will jump to this place again and
just cut off another element
*/
$x = array_slice($x , 1 );
}
print_r($result);

php arrays get the order number of a certain element

Lets say i have an array in PHP
$test['michael_unique_id'] = 3;
$test['john_unique_id'] = 8;
$test['mary_unique_id'] = 10;
.
.
.
.
$test['jimmy_unique_id'] = 4;
(the values (3,8,10.........4) are unique)
Lets say i want to search for the unique id 10, and get the order of the matching element in the array. In this example, the third element has the value 10, so i should get the number 3.
I can do it by scanning with a for loop looking for the value i'm searching and then get the $i value when i have a match, but i wonder if there is any built-in function (or a better method) that implements this.
You can get all of the array's values as an array with array_values() and then use array_search() to get the position (offset) of that value in the array.
$uniq_id = 10;
$all_vals = array_values($test); // => array(3, 8, 10, ... )
echo array_search( $uniq_id, $all_vals ); // => 2
Because PHP array indices are zero-based, you'll get 0 for the first item, 1 for the second item, etc. If you want the first item to be "1," then just add one. All together now:
$uniq_id = 10;
echo array_search( $uniq_id, array_values( $test ) ) + 1; // => 3
It's not clear to me, however, that this is necessarily as performant as just doing a foreach:
$uniq_id = 10;
$idx = 1;
foreach($test as $val) {
if($val == $uniq_id) {
break;
}
$idx++;
}
echo $idx; // => 3
Well, array_search will give you the key, but in your case, you want the index of that key, so I believe a loop is your best bet. Is there a good reason why you need the index? It doesn't seem very useful to me.

Looking up keys for a multi-dimensional array

I have an array with a key and 3 values (day, start_time, end_time). I want to keep adding certain entries into this array while making sure each entry is unique. That means that every time I try to add an item into the array, I want to make sure it does not already exist in it. If it does exist, I want to be able to find the key that indicates that entry.
For example, this is the pre-existing array:
$array [0][0] = Monday
$array [0][1] = 2
$array [0][2] = 4
$array [1][0] = Tuesday
$array [1][1] = 3
$array [1][2] = 5
If I try to insert (Wednesday, 3, 5), then it should make the entry in the index 2.
If I try to insert (Monday, 2, 4), I need to be able to know that it is already in there and is indexed by 0.
How do I go about doing this?
I agree with the other answers here — it might be better to restructure your array so that there is no need to worry about duplication at all.
If you want to keep your current structure, however: use array_search.
$array = ...
$unique_check = array_search(array('Monday', 2, 4), $array);
if ( $unique_check === false )
// add to array
else
// $unique_check = the array key at which the existing matching element is located
Why not organize the array this way?
$array [Monday][0] = 2
$array [Monday][1] = 4
$array [Tuesday][0] = 3
$array [Tuesday][1] = 5

Categories