I have done a lot of researching, and I cant find out how to delete an element from an array in PHP. In Java, if you have an ArrayList<SomeObject> list, you would say list.remove(someObject);.
Is there anything similar you can do in PHP? I have found unset($array[$index]);, but it doesnt seem to work.
Thanks for your help in advance!
unset should work, you can also try this:
$array = array_merge(
array_slice($array, 0, $index),
array_slice($array, $index+1)
);
You need to either remove it and remove the empty array:
function remove_empty($ar){
$aar = array();
while(list($key, $val) = each($ar)){
if (is_array($val)){
$val = remove_empty($val);
if (count($val)!=0){
$aar[$key] = $val;
}
}
else {
if (trim($val) != ""){
$aar[$key] = $val;
}
}
}
unset($ar);
return $aar;
}
remove_empty(array(1,2,3, '', 5)) returns array(1,2,3,5)
unset($array[$index]); actually works.
The only issue I can think of is the way you're iterating this array.
just use foreach instead of for
also make sure that $index contains correct value
to test your array you can use var_dump():
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
unset($cars[0]);
var_dump($cars);
If you want to delete just one array element you can use unset() or alternative array_splice()
Unset()
Example :
Code
<?php
$array = array(0 => "x", 1 => "y", 2 => "z");
unset($array[1]);
//If you want to delete the second index ie, array[1]
?>
Output
Array (
[0] => a
[2] => c
)
Related
$arr = array('a' => 1, 'b' => 2);
$xxx = &$arr['a'];
unset($xxx);
print_r($arr); // still there :(
so unset only breaks the reference...
Do you know a way to unset the element in the referenced array?
Yes, I know I could just use unset($arr['a']) in the code above, but this is only possible when I know exactly how many items has the array, and unfortunately I don't.
This question is kind of related to this one (this is the reason why that solution doesn't work)
I may be wrong but I think the only way to unset the element in the array would be to look up the index that matches the value referenced by the variable you have, then unsetting that element.
$arr = array('a' => 1, 'b' => 2);
$xxx = &$arr['a'];
$keyToUnset = null;
foreach($arr as $key => $value)
{
if($value === $xxx)
{
$keyToUnset = $key;
break;
}
}
if($keyToUnset !== null)
unset($arr[$keyToUnset]);
$unset($xxx);
Well, anyway, something along those lines. However, keep in mind that this is not super efficient because each time you need to unset an element you have to iterate over the full array looking for it.
Assuming you have control over how $xxx is used, you may want to consider using it to hold the key in the array, instead of a reference to the element at the key. That way you wouldn't need to search the array when you wanted to unset the element. But you would have to replace all sites that use $xxx with an array dereference:
$arr = array('a' => 1, 'b' => 2);
$xxx = 'a';
// instead of $xxx, use:
$arr[$xxx];
// to unset, simply
unset($arr[$xxx]);
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed.
And with respect to the code above - I do not think there is need in separate key
foreach($arr as $key => $value)
{
if($value === $xxx)
{
unset($arr[$key]);
break;
}
}
The simple answer:
$arr = array('a' => 1, 'b' => 2);
$xxx = 'a';
unset($arr[$xxx]);
print_r($arr); // gone :)
i.e.. You probably don't ever really need a reference. Just set $xxx to the appropriate key.
I know there is array_unique function, but I want to remove duplicates. Is there a built-in function or do I have to roll my own.
Example input:
banna, banna, mango, mango, apple
Expected output:
apple
You can use a combination of array_unique, array_diff_assoc and array_diff:
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
You can use
$singleOccurences = array_keys(
array_filter(
array_count_values(
array('banana', 'mango', 'banana', 'mango', 'apple' )
),
function($val) {
return $val === 1;
}
)
)
See
array_count_values — Counts all the values of an array
array_filter — Filters elements of an array using a callback function
array_keys — Return all the keys or a subset of the keys of an array
callbacks
Just write your own simple foreach loop:
$used = array();
$array = array("banna","banna","mango","mango","apple");
foreach($array as $arrayKey => $arrayValue){
if(isset($used[$arrayValue])){
unset($array[$used[$arrayValue]]);
unset($array[$arrayKey]);
}
$used[$arrayValue] = $arrayKey;
}
var_dump($array); // array(1) { [4]=> string(5) "apple" }
have fun :)
If you want to only leave values in the array that are already unique, rather than select one unique instance of each value, you will indeed have to roll your own. Built in functionality is just there to sanitise value sets, rather than filter.
You want to remove any entries that have duplicates, so that you're left with only the entries that were unique in the list?
Hmm it does sound like something you'll need to roll your own.
There is no existing function; You'll have to do this in two passes, one to count the unique values and one to extract the unique values:
$count = array();
foreach ($values as $value) {
if (array_key_exists($value, $count))
++$count[$value];
else
$count[$value] = 1;
}
$unique = array();
foreach ($count as $value => $count) {
if ($count == 1)
$unique[] = $value;
}
The answer on top looks great, but on a side note: if you ever want to eliminate duplicates but leave the first one, using array_flip twice would be a pretty simple way to do so. array_flip(array_flip(x))
Only partially relevant to this specific question - but I created this function from Gumbo's answer for multi dimensional arrays:
function get_default($array)
{
$default = array_column($array, 'default', 'id');
$array = array_diff($default, array_diff_assoc($default, array_unique($default)));
return key($array);
}
In this example, I had cached statuses and each one other than the default was 0 (the default was 1). I index the default array from the IDs, and then turn it into a string. So to be clear - the returned result of this is the ID of the default status providing it's in the same part of the multi dimensional array and not the key of it
PHP.net http://php.net/manual/en/function.array-unique.php
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
New solution:
function remove_dupes(array $array){
$ret_array = array();
foreach($array as $key => $val){
if(count(array_keys($val) > 1){
continue;
} else {
$ret_array[$key] = $val;
}
}
Each item in my array is an array of about 5 values.. Some of them are numerical ending in "GB".. I need the same array but with "GB" stripped out so that just the number remains.
So I need to iterate through my whole array, on each subarray take each value and strip the string "GB" from it and create a new array from the output.
Can anyone recommend and efficient method of doing this?
You can use array_walk_recursive() for this:
array_walk_recursive($arr, 'strip_text', 'GB');
function strip_text(&$value, $key, $string) {
$value = str_replace($string, '', $value);
}
It's a lot less awkward than traversing an array with its values by reference (correctly).
You can create your own custom function to iterate through an array's value's, check if the substring GB exists, and if so, remove it. With that function you can pass the original array and the function into array_map
// i only did the subarray part
$diskSizes = array("500", "300 GB", "200", "120 GB", "130GB");
$newArray = array();
foreach ($diskSizes as $diskSize) {
$newArray[] = str_replace('GB', '', $diskSize);
}
// look at the new array
print_r($newArray);
$arr = ...
foreach( $arr as $k => $inner ) {
foreach( $inner as $kk => &$vv ) {
$vv = str_replace( 'GB', '', $vv );
}
}
This actually keeps the original arrays intact with the new strings. (notice &$vv, which means that i'm getting the variable by reference, which means that any changes to $vv within the loop will affect the actual string, not by copying)
If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?
reset() gives you the first value of the array if you have an element inside the array:
$value = reset($array);
It also gives you FALSE in case the array is empty.
PHP < 7.3
If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.
So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:
$value = empty($arr) ? $default : reset($arr);
The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:
$value = $default;
foreach(array_slice($arr, 0, 1) as $value);
Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:
foreach(array_slice($arr, 0, 1, true) as $key => $value);
To get the first item as a pair (key => value):
$item = array_slice($arr, 0, 1, true);
Simple modification to get the last item, key and value separately:
foreach(array_slice($arr, -1, 1, true) as $key => $value);
performance
If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:
$key = count($arr) ? array_keys($arr)[0] : null;
If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).
A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.
PHP 7.3+
PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.
So since PHP 7.3 the first value of $array may be accessed with
$array[array_key_first($array)];
You still had better check that the array is not empty though, or you will get an error:
$firstKey = array_key_first($array);
if (null === $firstKey) {
$value = "Array is empty"; // An error should be handled here
} else {
$value = $array[$firstKey];
}
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each() (warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.
$first = array_shift($array);
current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.
$first = current($array);
If you want to make sure that it is pointing to the first element, you can always use reset().
reset($array);
$first = current($array);
another easy and simple way to do it use array_values
array_values($array)[0]
Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
We can do
$first = reset($array);
Instead of
reset($array);
$first = current($array);
As reset()
returns the first element of the array after reset;
You can make:
$values = array_values($array);
echo $values[0];
Use reset() function to get the first item out of that array without knowing the key for it like this.
$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);
output //
400
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
You can try this.
To get first value of the array :-
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
var_dump(current($large_array));
?>
To get the first key of the array
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
$large_array_keys = array_keys($large_array);
var_dump(array_shift($large_array_keys));
?>
In one line:
$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];
Expanded:
$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
You could use array_values
$firstValue = array_values($array)[0];
You could use array_shift
I do this to get the first and last value. This works with more values too.
$a = array(
'foo' => 400,
'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz
For example i have an array like this:
$test= array("0" => "412", "1" => "2");
I would like to delete the element if its = 2
$delete=2;
for($j=0;$j<$dbj;$j++) {
if (in_array($delete, $test)) {
unset($test[$j]);
}
}
print_r($test);
But with this, unfortunatelly the array will empty...
How can i delete an exact element from the array?
Thank you
In the loop you're running the test condition is true because $delete exists in the array. So in each iteration its deleting the current element until $delete no longer exists in $test. Try this instead. It runs through the elements of the array (assuming $dbj is the number of elements in $delete) and if that element equals $delete it removes it.
$delete=2;
for($j=0;$j<$dbj;$j++) {
if ($test[$j]==$delete)) {
unset($test[$j]);
}
}
print_r($test);
What do you mean in exact?
I you would ike to delete element with key $key:
unset($array[$key]);
If specified value:
$key = array_search($value, $array);
unset($array[$key]);
Try
if( $test[$j] == $delete )
unset( $test[$j] );
What your current code does is search the whole array for $delete every time, and the unset the currently iterated value. You need to test the currently iterated value for equality with $delete before removing it from the array.
$key = array_search(2, $test);
unset($test[$key]);
To delete a specific item from an array, use a combination of array_search and array_splice
$a = array('foo', 'bar', 'baz', 'quux');
array_splice($a, array_search('bar', $a), 1);
echo implode(' ', $a); // foo baz quux