This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}
Related
I have a php array, and inside the array is a reference to another php object with a numerical value.
How can i access the elements in this array without knowing that numerical id (it could be different for each array)?
In the image below, I need to get the values inside field_collection_item like so....
$content['field_image_columns'][0]['entity']['field_collection_item'][133]['field_image']
For the first array key (0) i have done the following...
$i = 0;
while($i <= 2) {
if(isset($content['field_image_columns'][$i])) {
print '<div class="column-' . $i . '">';
foreach ($content['field_image_columns'][$i]['entity']['field_collection_item'] as $fcid => $values) {
// Print field values
}
print '</div>';
}
$i++;
}
Doing a foreach loop for a single array item seems wrong - is there a method i should be using for this use case?
You can select first item of array for example with:
Use array_shift, but it will modify source array:
$cur = array_shift($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
Get keys of array with array_keys and use first element of result as a key
$ks = array_keys($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $content['field_image_columns'][$i]['entity']['field_collection_item'][$ks[0]]['field_image'];
Use current function:
$cur = current($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
As with most programming, there are quite a few ways you could do it. If a foreach works, then it isn't wrong, but it may not be the best way.
// Get the current key from an array
$key = key($array);
If you don't need the key, then you can just get the value from the array.
// Get the current value from an array
$value = current($array);
Both of these will retrieve the first key/value from the array assuming you haven't advanced the pointer.
current, key, end, reset, next, & prev are all array functions that allow you to manipulate an array without knowing anything about the internals. http://php.net/manual/en/ref.array.php
I have a need to check if the elements in an array are objects or something else. So far I did it like this:
if((is_object($myArray[0]))) { ... }
However, on occasion situations dictate that the input array does not have indexes that start with zero (or aren't even numeric), therefore asking for $myArray[0] will generate a Notice, but will also return the wrong result in my condition if the first array element actually is an object (but under another index).
The only way I can think of doing here is a foreach loop where I would break out of it right on the first go.
foreach($myArray as $element) {
$areObjects = (is_object($element));
break;
}
if(($areObjects)) { ... }
But I am wondering if there is a faster code than this, because a foreach loop seems unnecessary here.
you can use reset() function to get first index data from array
if(is_object(reset($myArray))){
//do here
}
You could get an array of keys and get the first one:
$keys = array_keys($myArray);
if((is_object($myArray[$keys[0]]))) { ... }
try this
reset($myArray);
$firstElement = current($myArray);
current gets the element in the current index, therefore you should reset the pointer of the array to the first element using reset
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.reset.php
I want to unset a known value from an array. I could iterate with a for loop to look for the coincident value and then unset it.
<?php
for($i=0, $length=count($array); $i<$length; $i++)
{
if( $array[$i] === $valueToUnset )
//unset the value from the array
}
Any idea? Any way to achieve it without looping?
I am presuming that your intention is to get the index back, as you already have the value. I am further presuming that there is also a possibility that said value will NOT be in the array, and we have to account for that. I am not sure what you are using array_slice for. So, if I properly understand your requirements, a simple solution would be as follows:
<?php
$foundIndex = false; //Initialize variable that will hold index value
$foundIndex = array_search($valueToExtract, $array);
if($foundIndex === null) {
//Value was not found in the array
} else {
unset($array[$foundIndex]; //Unset the target element
}
?>
array_diff is the solution:
<?php
array_diff($array, array($valueToUnset));
No iteration needed.
I am trying to prevent duplicates from occuring in a final array. I am trying to check for duplicates in a list of $media_candidate objects and compile them:
$iterator = 0;
// ensure items in final array are unique
while ((count($final_array) < $numResults) && ($iterator < count($media_data))) {
$media_candidate = $media_data[$iterator++];
if(!in_array($media_candidate['id'], $final_array)){
$final_array[] = $media_candidate;
}
}
As you can see in a print out of $final_array the last three elements are appearing 3 times with id, 343050519221992426_18478933. Any ideas as to what's going on?
First of all: You do not truncate the final array, so that all doublettes will end up at the end.
Second: You are reinventing the wheel: Read up on array_unique()
Edit
Third: After your edit, there is an even easier way:
$final_array=array();
foreach($media_data as $m) $final_array[$m['id']]=$m;
//You might want the next line or not
$final_array=array_values($final_array);
In essence you outsource the uniqueness to the hash keys of the array.
Try with:
if(!in_array($media_candidate['id'], $final_array)){
$final_array[] = $media_candidate['id'];
}
With $final_array[] you add new element at the end of the array.
You are checking $media_candidate['id'] but inserting $media_candidate in $final_array
Try array_unique function like this
$final_array = array_unique($media_candidate);
This is supposed to take any rows where ing_name is duplicated, combine the eff_name fields and delete the duplicate but it also has the side effect of changing the array from numeric to associative. My ajax is expecting numeric array.
for($i=count($recipe)-1; $i>0; $i--) {
if($recipe[$i]['ing_name'] == $recipe[$i-1]['ing_name']) { //check for duplicate. **array must be sorted by ing_name**
$recipe[$i-1]['eff_name'] .= ', '.$recipe[$i]['eff_name']; //Combine eff_name of duplicates
$recipe[$i-1]['link'] = true;
unset($recipe[$i]); //remove duplicate index
}
}
examples: NUM, ASSOC
Source
EDIT: So i figured it must have something to do with unsetting the index so I did this and it seems to work ok:
$newRecipe = array();
foreach($recipe as $r) {
$newRecipe[] = $r;
}
New question, is there a better way?
unset works with named keys. You could use array_splice instead, or get a brand new array after the loop with array_values (but that would be ugly!).
array_values() Will return a numerically indexed array