Alternative to array_shift function - php

Ok, I need keys to be preserved within this array and I just want to shift the 1st element from this array. Actually I know that the first key of this array will always be 1 when I do this:
// Sort it by 1st group and 1st layout.
ksort($disabled_sections);
foreach($disabled_sections as &$grouplayout)
ksort($grouplayout);
Basically I'd rather not have to ksort it in order to grab this array where the key = 1. And, honestly, I'm not a big fan of array_shift, it just takes to long IMO. Is there another way. Perhaps a way to extract the entire array where $disabled_sections[1] is found without having to do a foreach and sorting it, and array_shift. I just wanna add $disabled[1] to a different array and remove it from this array altogether. While keeping both arrays keys structured the way they are. Technically, it would even be fine to do this:
$array = array();
$array = $disabled_sections[1];
But it needs to remove it from $disabled_sections. Can I use something like this approach...
$array = array();
$array = $disabled_sections[1];
$disabled_sections -= $disabled_sections[1];
Is something like the above even possible??
Thanks.

Despite there being an accepted answer to this; in case someone else stumbles across this, a way to unset the first element of an array (regardless of its key, or the order of its keys) without using array_shift is:
reset($array); // sets internal array pointer to start
unset($array[key($array)]); // key() returns key of current array element
Though I'm fairly convinced that's what array_shift does internally (so I imagine there would be no performance gain to this), excepting an additional return of the value retrieved:
$element = reset($array); // also returns element
unset($array[key($array)]);
return $element;
Just for completion's sake.

While there's no -= operator in that fashion, you can use unset to remove that element from an array:
unset(disabled_sections[1]);
But that's just implementing your own version of shift. I do wonder under what situation you're finding array_shift() to be 'slow' and how you're testing said slowness.
Numeric arrays are sorted numerical by default - no ksort is required. Maybe you should try something like
while($array = array_shift($group_of_arrays)) {
// ... do stuff
}
If you are not concerned about the order in which you pull elements out of the array, you can use "array_pop" instead of "array_shift". Since "array_pop" takes the elements off of the end of the array, no reindexing is required and performance increases dramatically. In testing with an array of about 80,000 entries I am seeing about a 90% decrease in processing time with "array_pop".

Related

Why should I use reset($arr) instead of $arr[0] in php to yield the first element of an Array in php? [duplicate]

Which one would you use?
Basically I only want to get the 1st element from a array, that's it.
Well, they do different things.
array_shift($arr) takes the first element out of the array, and gives it to you.
$arr[0] just gives it to you... if the array has numeric keys.
An alternative that works for associative arrays too is reset($arr). This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.
array_shift will actually remove the specified value from the array. Do not use it unless you really want to reduce the array!
See here: http://php.net/manual/en/function.array-shift.php
You would use $arr[ 0 ]; array_shift removes the first element from the array.
EDIT
This answer is actually somewhere between incomplete and plain out wrong but, because the comments of the two jon's I think that it should actually stay up so that others can see that discourse.
The right answer:
reset is the method to return the first defined index of the array. Even in non-associative arrays, this may not be the 0 index.
array_shift will remove and return the value which is found at reset
The OP made the assumption that $arr[0] is the first index is not accurate in that particular context.
$arr[0] only works if the array as numerical keys.
array_shift removes the element from the array and it modifies the array itself.
If you are not sure what the first key is , and you do not want to remove it from the array, you could use:
<?php
foreach($arr $k=>$v){
$value = $v;
break;
}
or even better:
<?php
reset($arr);
$value = current($arr);
If you have an associative Array you can also use reset($arr): It returns the first Element (doesn't remove), and sets the array pointer to this element.
But the fastest way is $arr[0].
Do you want to modify the arr array also? array_shift removes the first element of the array and returns it, thus the array has changed. $arr[0] merely gives you the first element.
I would use $arr[0] unless I explicitly wanted to modify the array. You may add code later to use the arr array and forget that it was modified.
given what you need, $arr[0] is preferrable, because it's faster. array_shift is used in other situations.
arrshift is more reliable and will always return the first element in the array, but this also modifies the array by removing that element.
arr[0] will fail if your array doesn't start at the 0 index, but leaves the array itself alone.
A more convoluted but reliable method is:
$keys = array_keys($arr);
$first = $arr[$keys[0]];
with array_shif you have two operations:
retrive the firs element
shift the array
if you access by index, actually you have only one operation.
If you want the first element of an array, use $arr[0] form. Advantages - Simplicity, Readability and Maintainability. Keep things straight forward.
Edit: Use index 0 only if you know that the array has default keys starting from 0.
If you don't want to change the array in question, use $arr[0] (which merely gets the first element), otherwise if you want to remove the first element of $arr from $arr, use array_shift($arr).
For example:
$arr=array(3,-6,2);
$foo=$arr[0]; //$foo==3 and $arr==array(3,-6,2).
$bar=array_shift($arr); //$bar==3 and $arr==array(-6,2).
ETA: As others have pointed out, be sure that your array isn't an associative array (ie the keys are 0,1,...,(sizeof($arr)-1)), otherwise this probably won't work.

foreach( ... ) key on only - is array_keys(...) the most efficient?

if I have some code like:
foreach(array_keys($array) as $key)
{
// work with the array
}
I have 2 questions
Is array_keys( ... ) called for every single iteration of foreach( ... )? Is it efficient?
If I was to compare speed and memory, is the code above faster/more efficient than
foreach($array as $key => $data )
{
// use $key only
}
1.) If array_keys($array) would be evaluated in every iteration, then i don't think, the position where you were last time could be remembered, since array_keys() would return a fresh array with keys every time, plus it would be really bad in terms of performance, so no. This goes for all expressions which evaluates as some form of iterable, and goes in the first part of a foreach.
2.) If you iterate on the whole array, then here is what happens:
a) array_keys() first extracts all the keys from your array, which kind of a mix of a List and a Hashmap (if you are familiar with java or some strongly typed oo language), and it might be really fast or really slow depending on the implementation of the arrays internal structure and the array_keys method. Then if you iterate on the array, you need to do a lookup in every iteration, like $value = $array[$currentlyIteratedKey]; which also needs some time, especially with string keys.
b) The foreach loop is a language construct (probably better optimized), and there is no additional lookup, you get the key and the value in every iteration, so i think it would be faster.
Hope it helps, correct me if I'm wrong!
1 - faster when use all array
2 - faster when need to "find" some key and break

php sort associative arrays by keys that those keys exist in other array

I have this array
$myArray=array(
'a'=>array('id'=>1,'text'=>'blabla1'),
'b'=>array('id'=>2,'text'=>'blabla2'),
'c'=>array('id'=>3,'text'=>'blabla3'),
'd'=>array('id'=>4,'text'=>'blabla4'),
);
and i want to sort the above array by the keys a,b,c,d, who exist in another array:
$tempArray=array('c','a','d','b');
How can I do that so the $myArray
looks like this:
$myArray=array(
'c'=>array('id'=>3,'text'=>'blabla3'),
'a'=>array('id'=>1,'text'=>'blabla1'),
'd'=>array('id'=>4,'text'=>'blabla4'),
'b'=>array('id'=>2,'text'=>'blabla2'),
);
thanks for helping me!
The simplest and likely most efficient way to do this is by iterating the array that holds the sort order and creating a new, sorted array:
$sorted = array();
foreach ($tempArray as $order) {
if (isset($myArray[$order])) {
$sorted[$order] = $myArray[$order];
}
}
print_r($sorted);
This works because associative arrays implicitly have an order of the order in which elements were added to the array.
See it working
EDIT
Any solution involving a sorting function will likely be much less efficient than this. This is because in order to do it you will need to use a function that takes a callback - this already has an implied overhead of the function call.
The sorting functions also work by comparing items, meaning that the complexity any of those solutions will be greater than that of this solution (the complexity of this is simply O(n)). Also, in order to derive the return value for the sorting function you would need to inspect the target array, finding the position of each of the keys being compared, for each comparison, adding even more complexity.

Arrays: array_shift($arr) or $arr[0]?

Which one would you use?
Basically I only want to get the 1st element from a array, that's it.
Well, they do different things.
array_shift($arr) takes the first element out of the array, and gives it to you.
$arr[0] just gives it to you... if the array has numeric keys.
An alternative that works for associative arrays too is reset($arr). This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.
array_shift will actually remove the specified value from the array. Do not use it unless you really want to reduce the array!
See here: http://php.net/manual/en/function.array-shift.php
You would use $arr[ 0 ]; array_shift removes the first element from the array.
EDIT
This answer is actually somewhere between incomplete and plain out wrong but, because the comments of the two jon's I think that it should actually stay up so that others can see that discourse.
The right answer:
reset is the method to return the first defined index of the array. Even in non-associative arrays, this may not be the 0 index.
array_shift will remove and return the value which is found at reset
The OP made the assumption that $arr[0] is the first index is not accurate in that particular context.
$arr[0] only works if the array as numerical keys.
array_shift removes the element from the array and it modifies the array itself.
If you are not sure what the first key is , and you do not want to remove it from the array, you could use:
<?php
foreach($arr $k=>$v){
$value = $v;
break;
}
or even better:
<?php
reset($arr);
$value = current($arr);
If you have an associative Array you can also use reset($arr): It returns the first Element (doesn't remove), and sets the array pointer to this element.
But the fastest way is $arr[0].
Do you want to modify the arr array also? array_shift removes the first element of the array and returns it, thus the array has changed. $arr[0] merely gives you the first element.
I would use $arr[0] unless I explicitly wanted to modify the array. You may add code later to use the arr array and forget that it was modified.
given what you need, $arr[0] is preferrable, because it's faster. array_shift is used in other situations.
arrshift is more reliable and will always return the first element in the array, but this also modifies the array by removing that element.
arr[0] will fail if your array doesn't start at the 0 index, but leaves the array itself alone.
A more convoluted but reliable method is:
$keys = array_keys($arr);
$first = $arr[$keys[0]];
with array_shif you have two operations:
retrive the firs element
shift the array
if you access by index, actually you have only one operation.
If you want the first element of an array, use $arr[0] form. Advantages - Simplicity, Readability and Maintainability. Keep things straight forward.
Edit: Use index 0 only if you know that the array has default keys starting from 0.
If you don't want to change the array in question, use $arr[0] (which merely gets the first element), otherwise if you want to remove the first element of $arr from $arr, use array_shift($arr).
For example:
$arr=array(3,-6,2);
$foo=$arr[0]; //$foo==3 and $arr==array(3,-6,2).
$bar=array_shift($arr); //$bar==3 and $arr==array(-6,2).
ETA: As others have pointed out, be sure that your array isn't an associative array (ie the keys are 0,1,...,(sizeof($arr)-1)), otherwise this probably won't work.

PHP - Not getting the element I expect from an array

I am paging through the elements of an array.
I get the total number of elements in the array with:
$total = count($myarray);
My paging function loads the current element on the page and provides "Previous" and "Next" links that have urls like:
http://myapp.com?page=34
If you click the link I grab that and load it onto the page by getting (I sanitize the $_GET, this is just for example):
$element = $myarray[$_GET['page']];
This should grab the element of the array with a key == $_GET['page'] and it does. However, the problem is that my total count of elements doesn't match some keys because while there are 100 elements in the array, certain numbers are missing so the 100th item actually has a key of 102.
How should I be doing this? Do I need to rewrite the keys to match the available number of elements? Some other method? Thanks for your input.
If you have gaps in the indices, you should reindex the array. You can do that before you generate the links, or probably easier on the receiving page:
$myarray = array_values($myarray);
$element = $myarray[$_GET['page']];
This would give you the 100th element, even if it previously had the key 102. (You could use a temporary array of course, if you need to retain the original indexing.)
you can use
$array = array_values($array);
How should I be doing this? Do I need
to rewrite the keys to match the
available number of elements? Some
other method?
No you don't need to worry about them not matching. Php arrays are associative containers, like dictionaries in other languages. If you define something at 98 and 100, 99 isn't sitting there in memory, the data structure behind the associative container only stores whats there. You're not wasting space by not "filling it up" up to count.
So the practice you describe is fine. If there is no page "99" nothing need show up in your array. It may be nice, however, to see that your array doesn't have anything for the 'page' parameter and display an error message.
But then why, when I access $total =
count($myarray); $myarray[$total]
where $total = 100 I do not get the
last element? I can put page=101 and
get one more record. I should not be
able to do this
Because count is counting how many things are in the array. If you have an array with only the even elements filled in, ie:
$myArray[0] = "This";
$myArray[2] = "is";
$myArray[4] = "even";
Here count($myArray) is 3. There's nothing in [1] or [3]. Maybe this is easier to see when you take numbers out of the equation. Arrays can have string indexes
$myArray = array();
$myArray["Hello"] = "A Bunch of";
$myArray["World"] = "words";
Here count($myArray) is 2.
In the first case, it wouldn't make sense to access $myArray[3] because nothing is there. Clearly in the second example, there's nothing at 2.

Categories