How to remove post/product from usermeta? [duplicate] - php

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?
I thought that setting it to null would do it, but apparently it does not work.

There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a single array element
If you want to delete just one array element you can use unset() or alternatively \array_splice().
If you know the value and don’t know the key to delete the element you can use \array_search() to get the key. This only works if the element does not occur more than once, since \array_search returns the first hit only.
unset()
Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use \array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete
Output:
[
[0] => a
[2] => c
]
\array_splice() method
If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values(), which will convert all keys to numerical keys.
\array_splice() needs the offset, not the key, as the second parameter.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete
Output:
[
[0] => a
[1] => c
]
array_splice(), same as unset(), take the array by reference. You don’t assign the return values of those functions back to the array.
Deleting multiple array elements
If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.
\array_diff() method
If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset() it won’t change the keys of the array.
Code:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete
Output:
[
[1] => b
]
\array_diff_key() method
If you know the keys of the elements which you want to delete, then you want to use \array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete
Output:
[
[1] => b
]
If you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.
\array_filter() method
If you want to delete all elements with a specific value in the array you can use \array_filter().
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});
Output:
[
[0] => a
[1] => c
]

It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */

// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
This is the output from the code above:
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
Outputs
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)

$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}

unset($array[$index]);

Also, for a named element:
unset($array["elementName"]);

If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:
$my_array = array_diff($my_array, array('Value_to_remove'));
For example:
$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
This displays the following:
4
3
In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.

Destroy a single element of an array
unset()
$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);
The output will be:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[3]=>
string(1) "D"
[4]=>
string(1) "E"
}
If you need to re index the array:
$array1 = array_values($array1);
var_dump($array1);
Then the output will be:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "D"
[3]=>
string(1) "E"
}
Pop the element off the end of array - return the value of the removed element
mixed array_pop(array &$array)
$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array
The output will be
Array
(
[0] => orange
[1] => banana
[2] => apple
)
Last Fruit: raspberry
Remove the first element (red) from an array, - return the value of the removed element
mixed array_shift ( array &$array )
$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);
The output will be:
Array
(
[b] => green
[c] => blue
)
First Color: red

<?php
$stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
Output:
[
[0] => fruit2
[1] => fruit3
[2] => fruit4
]
fruit1

If the index is specified:
$arr = ['a', 'b', 'c'];
$index = 0;
unset($arr[$index]); // $arr = ['b', 'c']
If we have value instead of index:
$arr = ['a', 'b', 'c'];
// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);
if($index !== false){
unset($arr[$index]); // $arr = ['b', 'c']
}
The if condition is necessary
because if index is not found, unset() will automatically delete
the first element of the array which is not what we want.

If you have to delete multiple values in an array and the entries in that array are objects or structured data, array_filter() is your best bet. Those entries that return a true from the callback function will be retained.
$array = [
['x'=>1,'y'=>2,'z'=>3],
['x'=>2,'y'=>4,'z'=>6],
['x'=>3,'y'=>6,'z'=>9]
];
$results = array_filter($array, function($value) {
return $value['x'] > 2;
}); //=> [['x'=>3,'y'=>6,z=>'9']]

If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):
$my_array = array(
"key1" => "value 1",
"key2" => "value 2",
"key3" => "value 3",
"key4" => "value 4",
"key5" => "value 5",
);
$to_remove = array("key2", "key4");
$result = array_diff_key($my_array, array_flip($to_remove));
print_r($result);
Output:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )

Associative arrays
For associative arrays, use unset:
$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);
// RESULT: array('a' => 1, 'c' => 3)
Numeric arrays
For numeric arrays, use array_splice:
$arr = array(1, 2, 3);
array_splice($arr, 1, 1);
// RESULT: array(0 => 1, 1 => 3)
Note
Using unset for numeric arrays will not produce an error, but it will mess up your indexes:
$arr = array(1, 2, 3);
unset($arr[1]);
// RESULT: array(0 => 1, 2 => 3)

unset() destroys the specified variables.
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
<?php
function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
The answer of the above code will be bar.
To unset() a global variable inside of a function:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>

// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}

Solutions:
To delete one element, use unset():
unset($array[3]);
unset($array['foo']);
To delete multiple noncontiguous elements, also use unset():
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
To delete multiple contiguous elements, use array_splice():
array_splice($array, $offset, $length);
Further explanation:
Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:
$array[3] = $array['foo'] = '';
Besides syntax, there's a logical difference between using unset() and assigning '' to the element. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.
If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:
unset($products['XL1000']);
However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:
$products['XL1000'] = 0;
If you unset() an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1]; // Prints 'bee'
print $animals[2]; // Prints 'cat'
count($animals); // Returns 6
// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1]; // Prints '' and throws an E_NOTICE error
print $animals[2]; // Still prints 'cat'
count($animals); // Returns 5, even though $array[5] is 'fox'
// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1]; // Prints '', still empty
print $animals[6]; // Prints 'gnu', this is where 'gnu' ended up
count($animals); // Returns 6
// Assign ''
$animals[2] = ''; // Zero out value
print $animals[2]; // Prints ''
count($animals); // Returns 6, count does not decrease
To compact the array into a densely filled numeric array, use array_values():
$animals = array_values($animals);
Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
[0] => ant
[1] => bee
[2] => elk
[3] => fox
)
This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift() and array_pop(), respectively.

Follow the default functions:
PHP: unset
unset() destroys the specified variables. For more info, you can refer to PHP unset
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
PHP: array_pop
The array_pop() function deletes the last element of an array. For more info, you can refer to PHP array_pop
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
PHP: array_splice
The array_splice() function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_splice
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
PHP: array_shift
The array_shift() function removes the first element from an array. For more info, you can refer to PHP array_shift
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);

I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.

Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.
Solution #1
// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);
Solution #2
// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);
For this sample data:
$array = array(10 => "a", 20 => "b", 30 => "c");
You must have this result:
array(2) {
[20]=>
string(1) "b"
[30]=>
string(1) "c"
}

Edit
If you can't take it as given that the object is in that array you need to add a check:
if(in_array($object,$array)) unset($array[array_search($object,$array)]);
Original Answer
if you want to remove a specific object of an array by reference of that object you can do following:
unset($array[array_search($object,$array)]);
Example:
<?php
class Foo
{
public $id;
public $name;
}
$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';
$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';
$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';
$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);
echo '<pre>';
var_dump($array);
echo '</pre>';
?>
Result:
array(2) {
[0]=>
object(Foo)#1 (2) {
["id"]=>
int(1)
["name"]=>
string(5) "Name1"
}
[2]=>
object(Foo)#3 (2) {
["id"]=>
int(3)
["name"]=>
string(5) "Name3"
}
}
Note that if the object occures several times it will only be removed the first occurence!

unset() multiple, fragmented elements from an array
While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:
// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]
unset() dynamically
unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
Instead, unset() can be used dynamically in a foreach loop:
$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]
Remove array keys by copying the array
There is also another practice that has yet to be mentioned.
Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.
$array1 = range(1,10);
foreach ($array1 as $v) {
// Remove all even integers from the array
if( $v % 2 ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
Obviously, the same practice applies to text strings:
$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
// Remove all strings beginning with underscore
if( strpos($v,'_')===false ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 'foo', 'baz' ]

<?php
// If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
if (array_key_exists("key1", $my_array)) {
unset($my_array['key1']);
print_r($my_array);
}
else {
echo "Key does not exist";
}
?>
<?php
//To remove first array element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1);
print_r($new_array);
?>
<?php
echo "<br/> ";
// To remove first array element to length
// starts from first and remove two element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1, 2);
print_r($new_array);
?>
Output
Array ( [key1] => value 1 [key2] => value 2 [key3] =>
value 3 ) Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )

Remove an array element based on a key:
Use the unset function like below:
$a = array(
'salam',
'10',
1
);
unset($a[1]);
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
Remove an array element based on value:
Use the array_search function to get an element key and use the above manner to remove an array element like below:
$a = array(
'salam',
'10',
1
);
$key = array_search(10, $a);
if ($key !== false) {
unset($a[$key]);
}
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/

Use the following code:
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);

I came here because I wanted to see if there was a more elegant solution to this problem than using unset($arr[$i]). To my disappointment these answers are either wrong or do not cover every edge case.
Here is why array_diff() does not work. Keys are unique in the array, while elements are not always unique.
$arr = [1,2,2,3];
foreach($arr as $i => $n){
$b = array_diff($arr,[$n]);
echo "\n".json_encode($b);
}
Results...
[2,2,3]
[1,3]
[1,2,2]
If two elements are the same they will be remove. This also applies for array_search() and array_flip().
I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays. All the answers I am aware if here does not answer the question, and so here is a solution that will work.
$arr = [1,2,3];
foreach($arr as $i => $n){
$b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));
echo "\n".json_encode($b);
}
Results...
[2,3];
[1,3];
[1,2];
Since unset($arr[$i]) will work on both associative array and numeric arrays this still does not answer the question.
This solution is to compare the keys and with a tool that will handle both numeric and associative arrays. I use array_diff_uassoc() for this. This function compares the keys in a call back function.
$arr = [1,2,2,3];
//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];
foreach($arr as $key => $n){
$b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {
if($a != $b){
return 1;
}
});
echo "\n".json_encode($b);
}
Results.....
[2,2,3];
[1,2,3];
[1,2,2];
['b'=>'y','c'=>'x','d'=>'w'];
['a'=>'z','c'=>'x','d'=>'w'];
['a'=>'z','b'=>'y','d'=>'w'];
['a'=>'z','b'=>'y','c'=>'x'];

Related

Remove parts of a PHP Array [duplicate]

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?
I thought that setting it to null would do it, but apparently it does not work.
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a single array element
If you want to delete just one array element you can use unset() or alternatively \array_splice().
If you know the value and don’t know the key to delete the element you can use \array_search() to get the key. This only works if the element does not occur more than once, since \array_search returns the first hit only.
unset()
Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use \array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete
Output:
[
[0] => a
[2] => c
]
\array_splice() method
If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values(), which will convert all keys to numerical keys.
\array_splice() needs the offset, not the key, as the second parameter.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete
Output:
[
[0] => a
[1] => c
]
array_splice(), same as unset(), take the array by reference. You don’t assign the return values of those functions back to the array.
Deleting multiple array elements
If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.
\array_diff() method
If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset() it won’t change the keys of the array.
Code:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete
Output:
[
[1] => b
]
\array_diff_key() method
If you know the keys of the elements which you want to delete, then you want to use \array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete
Output:
[
[1] => b
]
If you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.
\array_filter() method
If you want to delete all elements with a specific value in the array you can use \array_filter().
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});
Output:
[
[0] => a
[1] => c
]
It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
This is the output from the code above:
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
Outputs
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)
$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}
unset($array[$index]);
Also, for a named element:
unset($array["elementName"]);
If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:
$my_array = array_diff($my_array, array('Value_to_remove'));
For example:
$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
This displays the following:
4
3
In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.
Destroy a single element of an array
unset()
$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);
The output will be:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[3]=>
string(1) "D"
[4]=>
string(1) "E"
}
If you need to re index the array:
$array1 = array_values($array1);
var_dump($array1);
Then the output will be:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "D"
[3]=>
string(1) "E"
}
Pop the element off the end of array - return the value of the removed element
mixed array_pop(array &$array)
$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array
The output will be
Array
(
[0] => orange
[1] => banana
[2] => apple
)
Last Fruit: raspberry
Remove the first element (red) from an array, - return the value of the removed element
mixed array_shift ( array &$array )
$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);
The output will be:
Array
(
[b] => green
[c] => blue
)
First Color: red
<?php
$stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
Output:
[
[0] => fruit2
[1] => fruit3
[2] => fruit4
]
fruit1
If the index is specified:
$arr = ['a', 'b', 'c'];
$index = 0;
unset($arr[$index]); // $arr = ['b', 'c']
If we have value instead of index:
$arr = ['a', 'b', 'c'];
// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);
if($index !== false){
unset($arr[$index]); // $arr = ['b', 'c']
}
The if condition is necessary
because if index is not found, unset() will automatically delete
the first element of the array which is not what we want.
If you have to delete multiple values in an array and the entries in that array are objects or structured data, array_filter() is your best bet. Those entries that return a true from the callback function will be retained.
$array = [
['x'=>1,'y'=>2,'z'=>3],
['x'=>2,'y'=>4,'z'=>6],
['x'=>3,'y'=>6,'z'=>9]
];
$results = array_filter($array, function($value) {
return $value['x'] > 2;
}); //=> [['x'=>3,'y'=>6,z=>'9']]
If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):
$my_array = array(
"key1" => "value 1",
"key2" => "value 2",
"key3" => "value 3",
"key4" => "value 4",
"key5" => "value 5",
);
$to_remove = array("key2", "key4");
$result = array_diff_key($my_array, array_flip($to_remove));
print_r($result);
Output:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )
Associative arrays
For associative arrays, use unset:
$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);
// RESULT: array('a' => 1, 'c' => 3)
Numeric arrays
For numeric arrays, use array_splice:
$arr = array(1, 2, 3);
array_splice($arr, 1, 1);
// RESULT: array(0 => 1, 1 => 3)
Note
Using unset for numeric arrays will not produce an error, but it will mess up your indexes:
$arr = array(1, 2, 3);
unset($arr[1]);
// RESULT: array(0 => 1, 2 => 3)
unset() destroys the specified variables.
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
<?php
function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
The answer of the above code will be bar.
To unset() a global variable inside of a function:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}
Solutions:
To delete one element, use unset():
unset($array[3]);
unset($array['foo']);
To delete multiple noncontiguous elements, also use unset():
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
To delete multiple contiguous elements, use array_splice():
array_splice($array, $offset, $length);
Further explanation:
Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:
$array[3] = $array['foo'] = '';
Besides syntax, there's a logical difference between using unset() and assigning '' to the element. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.
If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:
unset($products['XL1000']);
However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:
$products['XL1000'] = 0;
If you unset() an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1]; // Prints 'bee'
print $animals[2]; // Prints 'cat'
count($animals); // Returns 6
// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1]; // Prints '' and throws an E_NOTICE error
print $animals[2]; // Still prints 'cat'
count($animals); // Returns 5, even though $array[5] is 'fox'
// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1]; // Prints '', still empty
print $animals[6]; // Prints 'gnu', this is where 'gnu' ended up
count($animals); // Returns 6
// Assign ''
$animals[2] = ''; // Zero out value
print $animals[2]; // Prints ''
count($animals); // Returns 6, count does not decrease
To compact the array into a densely filled numeric array, use array_values():
$animals = array_values($animals);
Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
[0] => ant
[1] => bee
[2] => elk
[3] => fox
)
This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift() and array_pop(), respectively.
Follow the default functions:
PHP: unset
unset() destroys the specified variables. For more info, you can refer to PHP unset
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
PHP: array_pop
The array_pop() function deletes the last element of an array. For more info, you can refer to PHP array_pop
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
PHP: array_splice
The array_splice() function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_splice
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
PHP: array_shift
The array_shift() function removes the first element from an array. For more info, you can refer to PHP array_shift
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);
I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.
Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.
Solution #1
// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);
Solution #2
// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);
For this sample data:
$array = array(10 => "a", 20 => "b", 30 => "c");
You must have this result:
array(2) {
[20]=>
string(1) "b"
[30]=>
string(1) "c"
}
Edit
If you can't take it as given that the object is in that array you need to add a check:
if(in_array($object,$array)) unset($array[array_search($object,$array)]);
Original Answer
if you want to remove a specific object of an array by reference of that object you can do following:
unset($array[array_search($object,$array)]);
Example:
<?php
class Foo
{
public $id;
public $name;
}
$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';
$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';
$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';
$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);
echo '<pre>';
var_dump($array);
echo '</pre>';
?>
Result:
array(2) {
[0]=>
object(Foo)#1 (2) {
["id"]=>
int(1)
["name"]=>
string(5) "Name1"
}
[2]=>
object(Foo)#3 (2) {
["id"]=>
int(3)
["name"]=>
string(5) "Name3"
}
}
Note that if the object occures several times it will only be removed the first occurence!
unset() multiple, fragmented elements from an array
While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:
// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]
unset() dynamically
unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
Instead, unset() can be used dynamically in a foreach loop:
$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]
Remove array keys by copying the array
There is also another practice that has yet to be mentioned.
Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.
$array1 = range(1,10);
foreach ($array1 as $v) {
// Remove all even integers from the array
if( $v % 2 ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
Obviously, the same practice applies to text strings:
$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
// Remove all strings beginning with underscore
if( strpos($v,'_')===false ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 'foo', 'baz' ]
<?php
// If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
if (array_key_exists("key1", $my_array)) {
unset($my_array['key1']);
print_r($my_array);
}
else {
echo "Key does not exist";
}
?>
<?php
//To remove first array element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1);
print_r($new_array);
?>
<?php
echo "<br/> ";
// To remove first array element to length
// starts from first and remove two element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1, 2);
print_r($new_array);
?>
Output
Array ( [key1] => value 1 [key2] => value 2 [key3] =>
value 3 ) Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Remove an array element based on a key:
Use the unset function like below:
$a = array(
'salam',
'10',
1
);
unset($a[1]);
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
Remove an array element based on value:
Use the array_search function to get an element key and use the above manner to remove an array element like below:
$a = array(
'salam',
'10',
1
);
$key = array_search(10, $a);
if ($key !== false) {
unset($a[$key]);
}
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
Use the following code:
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
I came here because I wanted to see if there was a more elegant solution to this problem than using unset($arr[$i]). To my disappointment these answers are either wrong or do not cover every edge case.
Here is why array_diff() does not work. Keys are unique in the array, while elements are not always unique.
$arr = [1,2,2,3];
foreach($arr as $i => $n){
$b = array_diff($arr,[$n]);
echo "\n".json_encode($b);
}
Results...
[2,2,3]
[1,3]
[1,2,2]
If two elements are the same they will be remove. This also applies for array_search() and array_flip().
I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays. All the answers I am aware if here does not answer the question, and so here is a solution that will work.
$arr = [1,2,3];
foreach($arr as $i => $n){
$b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));
echo "\n".json_encode($b);
}
Results...
[2,3];
[1,3];
[1,2];
Since unset($arr[$i]) will work on both associative array and numeric arrays this still does not answer the question.
This solution is to compare the keys and with a tool that will handle both numeric and associative arrays. I use array_diff_uassoc() for this. This function compares the keys in a call back function.
$arr = [1,2,2,3];
//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];
foreach($arr as $key => $n){
$b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {
if($a != $b){
return 1;
}
});
echo "\n".json_encode($b);
}
Results.....
[2,2,3];
[1,2,3];
[1,2,2];
['b'=>'y','c'=>'x','d'=>'w'];
['a'=>'z','c'=>'x','d'=>'w'];
['a'=>'z','b'=>'y','d'=>'w'];
['a'=>'z','b'=>'y','c'=>'x'];

PHP array_push() get index? [duplicate]

This question already has answers here:
PHP get index of last inserted item in array
(6 answers)
Closed 4 years ago.
I'm looking for a way to push values into an array with automatic incremented keys. The porblem: I want to know the key of the inserted value.
Is there a way to do this? Insert values into an array and get the index of the inserted value?
The count of the array is not equal to the next insert-key, when an item gets removed from the array.
Thanks
Alex
A simple wrapper function around array_push() could help:
function array_push_autoinc(array &$array, $item) {
$next = sizeof($array);
$array[$next] = $item;
return $next;
}
You can use end() just after array_push. You will get the last insterted element.
end() advances array 's internal pointer to the last element, and returns its value.
key() returns the index element of the current array position.
Please have a look at below example:
$array = array(
'0' => 'one',
'1' => 'two',
'2' => 'three',
);
end($array); // move the pointer to the end of array
$key = key($array); // fetches the key of the element by the pointer
var_dump($key);
You can try one more solution, that will be faster.
$last_key = key( array_slice( $array, -1, 1, TRUE ) );
echo $last_key; //output "last"
Hope this will help you.
I found a solution:
This is my example-array:
$array = [2 => "two", 1 => "one", "four" => 4];
As you can see, there are strings and integers used as array-keys.
First of all I need to sort the array by its keys:
ksort($array);
Now the array looks like this:
$array = ["four" => 4, 1 => "one", 2 => "two"];
Now I can move the pointer to the end of the array and get the key (so I have the highest numeric key):
end($array);
$key = key($array);
I now increase the key by 1 and insert the value with the new key:
$key++;
$array[$key] = "three";
Now the key is saved in the variable $key and the array looks like this:
$array = ["four" => 4, 1 => "one", 2 => "two", 3 => "three"];
$key = 3;
That's it.
Now the complete code for all of you script-kiddies out there:
$array = [2 => "two", 1 => "one", "four" => 4];
ksort($array);
end($array);
$key = key($array);
$key++;
$array[$key] = "three";

Push columnar values of multiple arrays (of different lengths) to form a flat array

I have from 3 to 10 arrays containing 20 to 50 value each.
I want to merge them into a single, flat, indexed array, but not the way array_merge works.
I rather want to take the 1st value of the 1st array, then the 1st value of the second array, then the 1st value of the third array and so on.
Keys are not an issue here, It could be numerical or associative array, I'm just keeping the values, not the original keys.
Values in real application can be mixed so merging and sorting afterwards is not an option.
So if I had 3 arrays like so:
$array1 = array('1-1', '1-2', '1-3');
$array2 = array('2-1', '2-2', '2-3', '2-4');
$array3 = array('3-1', '3-2');
I would need the result to be an array containing the value in this order:
1-1, 2-1, 3-1, 1-2, 2-2, 3-2, 1-3, 2-3, 2-4
So far I have this piece of code :
$array = array($array1, $array2, $array3);
$newarray = array();
foreach ($array as $a) {
$v = array_shift($a);
if (isset($v)) {
$newarray[] = $v;
}
}
print_r($newarray);
but, of course, it only runs the 1st set of value and give me:
Array ( [0] => 1-1 [1] => 2-1 [2] => 3-1 )
array_shift is what I need here because it remove the value from the old array (I don't need it anymore) and I move it to the new array (if it isset). see: http://php.net/manual/en/function.array-shift.php
I'm pretty sure I will need a function and loop it until all arrays are empty, but I just can't wrap my head around this one. Any help will be greatly appreciated. Or even better if someone knows a native php function that does that.
Here's a simple one-liner...
$arr1 = ['1-1', '1-2', '1-3'];
$arr2 = ['2-1', '2-2', '2-3', '2-4'];
$arr3 = ['3-1', '3-2'];
$result = array_filter(call_user_func_array(array_merge, array_map(null, $arr1, $arr2, $arr3)));
So, maybe not so simple... Some explanation.
array_map(null, ...); makes use of the feature of array_map explained in example 4 of the PHP docs but without any transformation to the values (hence, null).
So, this will give you:
array(4) {
[0]=>
array(3) {
[0]=>
string(3) "1-1"
[1]=>
string(3) "2-1"
[2]=>
string(3) "3-1"
}
[1]=>
array(3) {
[0]=>
string(3) "1-2"
[1]=>
string(3) "2-2"
[2]=>
string(3) "3-2"
}
[2]=>
array(3) {
[0]=>
string(3) "1-3"
[1]=>
string(3) "2-3"
[2]=>
NULL
}
[3]=>
array(3) {
[0]=>
NULL
[1]=>
string(3) "2-4"
[2]=>
NULL
}
}
Then, we need to "flatten" the array, concatenating all the sub-arrays together.
This is achieved using array_merge, but that doesn't take an array, so we use call_user_func_array to feed the array into it's arguments.
Then the array_filter to remove the nulls (introduced by array_map due to the original arguments not being the same length).
Just added for reference, if you're running PHP 5.6+ you can take advantage of the new ... operator to signify n number of arguments in a function declaration and/or call. Implementation would be something like this (reference):
function merge_vertical(...$arrays) {
return array_filter(array_merge(...array_map(null, ...$arrays)));
}
print_r(merge_vertical($array1, $array2, $array3));
Output:
Array
(
[0] => 1-1
[1] => 2-1
[2] => 3-1
[3] => 1-2
[4] => 2-2
[5] => 3-2
[6] => 1-3
[7] => 2-3
[10] => 2-4
)
Try this code
$array1=array('1-1','1-2','1-3');
$array2=array('2-1','2-2','2-3','2-4');
$array3=array('3-1','3-2');
$array=array($array1,$array2,$array3);
$array2 = $array ;
function cmp($a, $b){
return (count($b) - count($a));
}
usort($array2, 'cmp');
$xax_length = count($array2[0]);
$newarray=array();
for($i=0;$i<$xax_length;$i++) {
foreach($array as &$a){
$v=array_shift($a);
if(isset($v)){
$newarray[]=$v;
}
}
}
print_r($newarray);
I would recommend hashing through all of the arrays in a for loop.
$array1=array('1-1','1-2','1-3');
$array2=array('2-1','2-2','2-3','2-4','2-5');
$array3=array('3-1','3-2');
$maxSize=max(count($array1),count($array2),count($array3));
$array=array($array1,$array2,$array3);
$newarray=array();
for ($i = 0; $i < $maxSize; $i++) {
for ($x = 0; $x < count($array); $x++) {
if(count($array[$x]) > $i){
$newarray[] = $array[$x][$i];
}
}
}
print_r($newarray);
While it is sexy to use array_map() to transpose array data so that columns of data can be easily extracted, the problem is that when processing data structures which are not perfectly shaped matrices, you will have null values generated.
Other answers fix the null population by calling array_filter() to mop up all of the unwanted nulls, but this will do harm to your result if you have false, null or zero-ish values in your data set that you actually wish to keep.
Also, this question states that key may be numeric or associative. This is another reason why transposing with array_map() is less attractive -- because it will choke on arrays with non-numeric keys.
While less elegant and sexy than some earlier posted answers, this answer wins out in terms of reliability because it will never destroy falsey values.
Add all arrays into a parent array (container), then iterate those arrays one at a time. "Shift" the first element off of each array and push it into the result array. If an array has no more elements, then unset() it so that it no longer occurs as a child of the parent array. (The original array variable will not be destroyed; only its copied version which exists inside the container.)
When the parent array has no more children, then stop looping.
Code: (Demo)
$array1 = [2 => 0, 0 => 1, 1 => '2'];
$array2 = [false, true, 'false' => false, 'true' => true];
$array3 = [null, 'null'];
$all = [$array1, $array2, $array3];
$result = [];
while ($all) {
foreach ($all as $index => &$array) {
$result[] = array_shift($array);
if (!$array) {
unset($all[$index]);
}
}
}
var_export($result);
Output:
array (
0 => 0,
1 => false,
2 => NULL,
3 => 1,
4 => true,
5 => 'null',
6 => '2',
7 => false,
8 => true,
)
You can use the + operator.
$c = $a + $b
Good luck !

How to remove values from an array whilst renumbering numeric keys

I have an array which may contain numeric or associative keys, or both:
$x = array('a', 'b', 'c', 'foo' => 'bar', 'd', 'e');
print_r($x);
/*(
[0] => a
[1] => b
[2] => c
[foo] => bar
[3] => d
[4] => e
)*/
I want to be able to remove an item from the array, renumbering the non-associative keys to keep them sequential:
$x = remove($x, "c");
print_r($x);
/* desired output:
(
[0] => a
[1] => b
[foo] => bar
[2] => d
[3] => e
)*/
Finding the right element to remove is no issue, it's the keys that are the problem. unset doesn't renumber the keys, and array_splice works on an offset, rather than a key (ie: take $x from the first example, array_splice($x, 3, 1) would remove the "bar" element rather than the "d" element).
This should re-index the array while preserving string keys:
$x = array_merge($x);
You can fixet with next ELEGANT solution:
For example:
<?php
$array = array (
1 => 'A',
2 => 'B',
3 => 'C'
);
unset($array[2]);
/* $array is now:
Array (
1 => 'A',
3 => 'C'
);
As you can see, the index '2' is missing from the array.
*/
// SOLUTION:
$array = array_values($array);
/* $array is now:
Array (
0 => 'A',
1 => 'C'
);
As you can see, the index begins from zero.
*/
?>
I've come up with this - though I'm not sure if it's the best:
// given: $arr is the array
// $item is the item to remove
$key = array_search($item, $arr); // the key we need to remove
$arrKeys = array_keys($arr);
$keyPos = array_search($key, $arrKeys); // the offset of the item in the array
unset($arr[$key]);
array_splice($arrKeys, $keyPos, 1);
for ($i = $keyPos; $i < count($arrKeys); ++$i) {
if (is_int($arrKeys[$i])) --$arrKeys[$i]; // shift numeric keys back one
}
$arr = array_combine($arrKeys, $arr); // recombine the keys and values.
There's a few things I've left out, just for the sake of brevity. For example, you'd check if the array is associative, and also if the key you're removing is a string or not before using the above code.
Try array_diff() it may not order the new array correctly though
if not the following should work
You will need to iterate over it in the remove function.
function remove($x,$r){
$c = 0;
$a = array();
foreach ($x as $k=>$v){
if ($v != $r) {
if (is_int($k)) {
$a[$c] = $v;
$c++;
}
else {
$a[$k] = $v;
}
}
}
return $a;
}
DC
I don't think there is an elegant solution to this problem, you probably need to loop to the array and reorder the keys by yourself.

Deleting an element from an array in PHP

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?
I thought that setting it to null would do it, but apparently it does not work.
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a single array element
If you want to delete just one array element you can use unset() or alternatively \array_splice().
If you know the value and don’t know the key to delete the element you can use \array_search() to get the key. This only works if the element does not occur more than once, since \array_search returns the first hit only.
unset()
Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use \array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete
Output:
[
[0] => a
[2] => c
]
\array_splice() method
If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values(), which will convert all keys to numerical keys.
\array_splice() needs the offset, not the key, as the second parameter.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete
Output:
[
[0] => a
[1] => c
]
array_splice(), same as unset(), take the array by reference. You don’t assign the return values of those functions back to the array.
Deleting multiple array elements
If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.
\array_diff() method
If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset() it won’t change the keys of the array.
Code:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete
Output:
[
[1] => b
]
\array_diff_key() method
If you know the keys of the elements which you want to delete, then you want to use \array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete
Output:
[
[1] => b
]
If you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.
\array_filter() method
If you want to delete all elements with a specific value in the array you can use \array_filter().
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});
Output:
[
[0] => a
[1] => c
]
It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
This is the output from the code above:
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
Outputs
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)
$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}
unset($array[$index]);
Also, for a named element:
unset($array["elementName"]);
If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:
$my_array = array_diff($my_array, array('Value_to_remove'));
For example:
$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
This displays the following:
4
3
In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.
Destroy a single element of an array
unset()
$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);
The output will be:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[3]=>
string(1) "D"
[4]=>
string(1) "E"
}
If you need to re index the array:
$array1 = array_values($array1);
var_dump($array1);
Then the output will be:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "D"
[3]=>
string(1) "E"
}
Pop the element off the end of array - return the value of the removed element
mixed array_pop(array &$array)
$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array
The output will be
Array
(
[0] => orange
[1] => banana
[2] => apple
)
Last Fruit: raspberry
Remove the first element (red) from an array, - return the value of the removed element
mixed array_shift ( array &$array )
$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);
The output will be:
Array
(
[b] => green
[c] => blue
)
First Color: red
<?php
$stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
Output:
[
[0] => fruit2
[1] => fruit3
[2] => fruit4
]
fruit1
If the index is specified:
$arr = ['a', 'b', 'c'];
$index = 0;
unset($arr[$index]); // $arr = ['b', 'c']
If we have value instead of index:
$arr = ['a', 'b', 'c'];
// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);
if($index !== false){
unset($arr[$index]); // $arr = ['b', 'c']
}
The if condition is necessary
because if index is not found, unset() will automatically delete
the first element of the array which is not what we want.
If you have to delete multiple values in an array and the entries in that array are objects or structured data, array_filter() is your best bet. Those entries that return a true from the callback function will be retained.
$array = [
['x'=>1,'y'=>2,'z'=>3],
['x'=>2,'y'=>4,'z'=>6],
['x'=>3,'y'=>6,'z'=>9]
];
$results = array_filter($array, function($value) {
return $value['x'] > 2;
}); //=> [['x'=>3,'y'=>6,z=>'9']]
If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):
$my_array = array(
"key1" => "value 1",
"key2" => "value 2",
"key3" => "value 3",
"key4" => "value 4",
"key5" => "value 5",
);
$to_remove = array("key2", "key4");
$result = array_diff_key($my_array, array_flip($to_remove));
print_r($result);
Output:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )
Associative arrays
For associative arrays, use unset:
$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);
// RESULT: array('a' => 1, 'c' => 3)
Numeric arrays
For numeric arrays, use array_splice:
$arr = array(1, 2, 3);
array_splice($arr, 1, 1);
// RESULT: array(0 => 1, 1 => 3)
Note
Using unset for numeric arrays will not produce an error, but it will mess up your indexes:
$arr = array(1, 2, 3);
unset($arr[1]);
// RESULT: array(0 => 1, 2 => 3)
unset() destroys the specified variables.
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
<?php
function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
The answer of the above code will be bar.
To unset() a global variable inside of a function:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}
Solutions:
To delete one element, use unset():
unset($array[3]);
unset($array['foo']);
To delete multiple noncontiguous elements, also use unset():
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
To delete multiple contiguous elements, use array_splice():
array_splice($array, $offset, $length);
Further explanation:
Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:
$array[3] = $array['foo'] = '';
Besides syntax, there's a logical difference between using unset() and assigning '' to the element. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.
If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:
unset($products['XL1000']);
However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:
$products['XL1000'] = 0;
If you unset() an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1]; // Prints 'bee'
print $animals[2]; // Prints 'cat'
count($animals); // Returns 6
// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1]; // Prints '' and throws an E_NOTICE error
print $animals[2]; // Still prints 'cat'
count($animals); // Returns 5, even though $array[5] is 'fox'
// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1]; // Prints '', still empty
print $animals[6]; // Prints 'gnu', this is where 'gnu' ended up
count($animals); // Returns 6
// Assign ''
$animals[2] = ''; // Zero out value
print $animals[2]; // Prints ''
count($animals); // Returns 6, count does not decrease
To compact the array into a densely filled numeric array, use array_values():
$animals = array_values($animals);
Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
[0] => ant
[1] => bee
[2] => elk
[3] => fox
)
This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift() and array_pop(), respectively.
Follow the default functions:
PHP: unset
unset() destroys the specified variables. For more info, you can refer to PHP unset
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
PHP: array_pop
The array_pop() function deletes the last element of an array. For more info, you can refer to PHP array_pop
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
PHP: array_splice
The array_splice() function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_splice
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
PHP: array_shift
The array_shift() function removes the first element from an array. For more info, you can refer to PHP array_shift
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);
I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.
Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.
Solution #1
// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);
Solution #2
// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);
For this sample data:
$array = array(10 => "a", 20 => "b", 30 => "c");
You must have this result:
array(2) {
[20]=>
string(1) "b"
[30]=>
string(1) "c"
}
Edit
If you can't take it as given that the object is in that array you need to add a check:
if(in_array($object,$array)) unset($array[array_search($object,$array)]);
Original Answer
if you want to remove a specific object of an array by reference of that object you can do following:
unset($array[array_search($object,$array)]);
Example:
<?php
class Foo
{
public $id;
public $name;
}
$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';
$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';
$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';
$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);
echo '<pre>';
var_dump($array);
echo '</pre>';
?>
Result:
array(2) {
[0]=>
object(Foo)#1 (2) {
["id"]=>
int(1)
["name"]=>
string(5) "Name1"
}
[2]=>
object(Foo)#3 (2) {
["id"]=>
int(3)
["name"]=>
string(5) "Name3"
}
}
Note that if the object occures several times it will only be removed the first occurence!
unset() multiple, fragmented elements from an array
While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:
// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]
unset() dynamically
unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
Instead, unset() can be used dynamically in a foreach loop:
$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]
Remove array keys by copying the array
There is also another practice that has yet to be mentioned.
Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.
$array1 = range(1,10);
foreach ($array1 as $v) {
// Remove all even integers from the array
if( $v % 2 ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
Obviously, the same practice applies to text strings:
$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
// Remove all strings beginning with underscore
if( strpos($v,'_')===false ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 'foo', 'baz' ]
<?php
// If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
if (array_key_exists("key1", $my_array)) {
unset($my_array['key1']);
print_r($my_array);
}
else {
echo "Key does not exist";
}
?>
<?php
//To remove first array element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1);
print_r($new_array);
?>
<?php
echo "<br/> ";
// To remove first array element to length
// starts from first and remove two element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1, 2);
print_r($new_array);
?>
Output
Array ( [key1] => value 1 [key2] => value 2 [key3] =>
value 3 ) Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Remove an array element based on a key:
Use the unset function like below:
$a = array(
'salam',
'10',
1
);
unset($a[1]);
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
Remove an array element based on value:
Use the array_search function to get an element key and use the above manner to remove an array element like below:
$a = array(
'salam',
'10',
1
);
$key = array_search(10, $a);
if ($key !== false) {
unset($a[$key]);
}
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
Use the following code:
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
I came here because I wanted to see if there was a more elegant solution to this problem than using unset($arr[$i]). To my disappointment these answers are either wrong or do not cover every edge case.
Here is why array_diff() does not work. Keys are unique in the array, while elements are not always unique.
$arr = [1,2,2,3];
foreach($arr as $i => $n){
$b = array_diff($arr,[$n]);
echo "\n".json_encode($b);
}
Results...
[2,2,3]
[1,3]
[1,2,2]
If two elements are the same they will be remove. This also applies for array_search() and array_flip().
I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays. All the answers I am aware if here does not answer the question, and so here is a solution that will work.
$arr = [1,2,3];
foreach($arr as $i => $n){
$b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));
echo "\n".json_encode($b);
}
Results...
[2,3];
[1,3];
[1,2];
Since unset($arr[$i]) will work on both associative array and numeric arrays this still does not answer the question.
This solution is to compare the keys and with a tool that will handle both numeric and associative arrays. I use array_diff_uassoc() for this. This function compares the keys in a call back function.
$arr = [1,2,2,3];
//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];
foreach($arr as $key => $n){
$b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {
if($a != $b){
return 1;
}
});
echo "\n".json_encode($b);
}
Results.....
[2,2,3];
[1,2,3];
[1,2,2];
['b'=>'y','c'=>'x','d'=>'w'];
['a'=>'z','c'=>'x','d'=>'w'];
['a'=>'z','b'=>'y','d'=>'w'];
['a'=>'z','b'=>'y','c'=>'x'];

Categories