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
Related
From a given array (eg: $_SERVER), I need to get the first and last key and value. I was trying use array_shift to get first value and key but what I get is value.
Here is the $_SERVER array:
print_r($_SERVER, true))
And I tried with:
echo array_shift($_SERVER);
With PHP >= 7.3 you can get it fast, without modification of the array and without creating array copies:
$first_key = array_key_first($_SERVER);
$first_value = $_SERVER[$first_key];
$last_key = array_key_last($_SERVER);
$last_value = $_SERVER[$last_key];
See array_key_first and array_key_last.
It's not clear if you want the value, or the key. This is about as efficient as it gets, if memory usage is important.
If you want the key, use array_keys. If you want the value, just refer to it with the key you got from array_keys.
$count = count($_SERVER);
if ($count > 0) {
$keys = array_keys($_SERVER);
$firstKey = $keys[0];
$lastKey = $keys[$count - 1];
$firstValue = $array[$firstKey];
$lastValue = $array[$lastKey];
}
You can't use $count - 1 or 0 to get the first or last value in keyed arrays.
You can do a foreach loop, and break out after the first one:
foreach ( $_SERVER as $key => $value ) {
//Do stuff with $key and $value
break;
}
Plenty of other methods here. You can pick and choose your favorite flavor there.
Separate out keys and values in separate arrays, and extract first and last from them:
// Get all the keys in the array
$all_keys = array_keys($_SERVER);
// Get all the values in the array
$all_values = array_values($_SERVER);
// first key and value
$first_key = array_shift($all_keys);
$first_value = array_shift($all_values);
// last key and value (we dont care about the pointer for the temp created arrays)
$last_key = end($all_keys);
$last_value = end($all_values);
/* you can use reset function after end function call
if you worry about the pointer */
What about this:
$server = $_SERVER;
echo array_shift(array_values($server));
echo array_shift(array_keys($server));
reversed:
$reversed = array_reverse($server);
echo array_shift(array_values($reversed));
echo array_shift(array_keys($reversed));
I think array_slice() will do the trick for you.
<?php
$a = array_slice($_SERVER, 0, 1);
$b = array_slice($_SERVER, -1, 1, true);
//print_r($_SERVER);
print_r($a);
print_r($b);
?>
OUTPUT
Array ( [TERM] => xterm )
Array ( [argc] => 1 )
DEMO: https://3v4l.org/GhoFm
I have two arrays containing repeating values:
$test1 = Array(
"blah1",
"blah1",
"blah1",
"blah1",
"blah2"
);
$test2 = Array(
"blah1",
"blah1",
"blah1",
"blah2"
);
I am trying to get array difference:
$result = array_diff($test1,$test2);
echo "<pre>";
print_r($result);
I need it to return array with single value blah1, yet it returns empty array instead...
I suspect it has something to do with fact there are duplicate values in both arrays, but not sure how to fix it...
Please help!!
EDIT:
End up writing this function to do the trick:
function subtract_array($array1,$array2){
foreach ($array2 as $item) {
$key = array_search($item, $array1);
unset($array1[$key]);
}
return array_values($array1);
}
array_diff compares the first array to the other array(s) passed as parameter(s) and returns an array, containing all the elements present in the first array that are not present in any other arrays. Since $test1 and $test2 both contain "blah1" and "blah2", and no other values, actually, the expected behavior of array_diff is the one that you have experienced, that is, to return an empty array, since, there is no element in $test1 which is not present in $test2.
Further read. Also, read some theory to understand what you are working with.
Spotted a problem with Acidon's own solution. The problem comes from the fact that unset($array[false]) will actually unset $array[0], so there needs to be an explicit check for false (as David Rodrigues pointed out as well.)
function subtract_array($array1,$array2){
foreach ($array2 as $item) {
$key = array_search($item, $array1);
if ( $key !== false ) {
unset($array1[$key]);
}
}
return array_values($array1);
}
Some examples
subtract_array([1,1,1,2,3],[1,2]); // [1,1,3]
subtract_array([1,2,3],[4,5,6]); // [1,2,3]
subtract_array([1,2,1],[1,1,2]); // []
subtract_array([1,2,3],[]); // [1,2,3]
subtract_array([],[1,1]); // []
subtract_array(['hi','bye'], ['bye', 'bye']); // ['hi']
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
)
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;
}
}
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