Although an array in PHP is "a type that associates values to keys" and some say it's not possible to remove the keys, you might, in a sense, remove the keys from an array either replacing the keys or replacing the array with another array.
I suppose you would like to change the array to an array equivalent to an array initialized without explicit keys. For instance, you might have this array:
$arr = array(2 => 'a', 3 => 'b', 4 => 'c');
But you'd like it to be equivalent to:
$arr = array('a', 'b', 'c');
It's possible to do it using the function "array_values", like this:
$arr = array_values($arr);
Notice, though, the array still has keys: 0, 1, 2, and 3.
It's important to note that the integer keys are not the same as the array indexes. For instance, this piece of code:
<?php
$arr = array(3 => '', 4 => '', 1 => '', 2 => '');
foreach(
k => $v):
echo "$k ";
endforeach;
will output:
3 4 1 2
The function "array_values" might be used to make sure the keys values and indexes are the same:
<?php
$arr = array(3 => '', 4 => '', 1 => '', 2 => '');
foreach(array_values(
k => $v):
echo "$k ";
endforeach;
// outputs: 0, 1, 2, 3
I explained how to "remove" the keys, but you might want to implement a class for the topics, make an interface for topic contents (animations, images, etc.) and check the SPL data structures.
Answer from Pedro Amaral Couto on Stack OverflowAlthough an array in PHP is "a type that associates values to keys" and some say it's not possible to remove the keys, you might, in a sense, remove the keys from an array either replacing the keys or replacing the array with another array.
I suppose you would like to change the array to an array equivalent to an array initialized without explicit keys. For instance, you might have this array:
$arr = array(2 => 'a', 3 => 'b', 4 => 'c');
But you'd like it to be equivalent to:
$arr = array('a', 'b', 'c');
It's possible to do it using the function "array_values", like this:
$arr = array_values($arr);
Notice, though, the array still has keys: 0, 1, 2, and 3.
It's important to note that the integer keys are not the same as the array indexes. For instance, this piece of code:
<?php
$arr = array(3 => '', 4 => '', 1 => '', 2 => '');
foreach(
k => $v):
echo "$k ";
endforeach;
will output:
3 4 1 2
The function "array_values" might be used to make sure the keys values and indexes are the same:
<?php
$arr = array(3 => '', 4 => '', 1 => '', 2 => '');
foreach(array_values(
k => $v):
echo "$k ";
endforeach;
// outputs: 0, 1, 2, 3
I explained how to "remove" the keys, but you might want to implement a class for the topics, make an interface for topic contents (animations, images, etc.) and check the SPL data structures.
Is it possible.?
No its not possible.You cannot remove the keys from arrays.If you want a string like that then you can try with implode function in php like this.
<?php
$arr = array(
2 => 'Title: Warmly little before cousin sussex entire set Blessing it ladyship.',
3 => 'Snippet: Testing',
4 => 'Category: Member',
5 => 'Tags: little, before, entire'
);
echo implode(",\n", $arr);
?>
Which will produce an output like this
Title: Warmly little before cousin sussex entire set Blessing it ladyship.,Snippet: Testing,Category: Member,Tags: little, before, entire
You can check the documentation of implode here for more info.
Easy way to remove all elements of an associative array with specified key?
Deleting an element from an array in PHP - Stack Overflow
PHP remove array keys - Stack Overflow
php - Efficient way to remove key-value from Array of Arrays - Stack Overflow
I have an array such as:
[0] => [
"id" => 568,
"first name" => "Greg",
"last name" => "Vinall"
],
[1] => [
"id" => 6,
"first name" => "Fred",
"last name" => "Nurd"
],
[2] => [
"id" => 56,
"first name" => "Mary",
"last name" => "Quant"
]I'd like to delete all elements whose key is "id", so that each array will only contain "first name" and "last name" keys and their associated values.
Is there a neat way to accomplish this, using a PHP array function?
To further the problem, I have another array: ["id" => "hidden, memberSource", "first name" => "member" ]
It is from this array that I find that it is the 'id" array that I want to remove because it contains the value "hidden".
Thanks.
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 single array element you can use unset() and alternatively array_splice().
By key or by value?
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 doesn't occur more than once, since array_search() returns the first hit only.
unset() Expression
Note: 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
(the array remains a list).
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key of element to delete
Example Output:
[
[0] => a
[2] => c
]
array_splice() Function
If you use array_splice() the (integer) keys will automatically be reindex-ed,
but the associative (string) keys won't change — as opposed to array_values() after unset(),
which will convert all keys to numerical keys.
Note: array_splice()
needs the offset, not the key, as the second parameter; offset = array_flip(array_keys(array))[key].
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
array_splice($array, 1, 1);
// ↑ Offset of element to delete
Example Output:
[
[0] => a
[1] => c
]
array_splice(), same as unset(), take the array by reference. You don’t assign the return values 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 to remove from the array.
array_diff() Function
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.
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = array_diff($array, ["a", "c"]);
// └────────┘
// Array values to delete
Example Output:
[
[1] => b
]
array_diff_key() Function
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.
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys of elements to delete
Example 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() Function
If you want to delete all elements with a specific value in the array you can use array_filter().
Example 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
});
Example Output:
[
[0] => a
[2] => 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)
} */
You need array_values($b) in order to re-key the array so the keys are sequential and numeric (starting at 0).
The following should do the trick:
$b = array(123,456,789,123);
unset($b[1]);
$b = array_values($b);
echo "<pre>"; print_r($b);
It is represented that your input data is an indexed array (there are no gaps in the sequence of the integer keys which start from zero). I'll compare the obvious techniques that directly deliver the desired result from the OP's sample data.
1. unset() then array_values()
unset($b[1]);
$b = array_value($b);
- This is safe to use without checking for the existence of the index -- if missing, there will be no error.
unset()can receive multiple parameters, so if more elements need to be removed, then the number of function calls remains the same. e.g.unset($b[1], $b[3], $b[5]);unset()cannot be nested inside ofarray_values()to form a one-liner becauseunset()modifies the variable and returns no value.- AFAIK,
unset()is not particularly handy for removing elements using a dynamic whitelist/blacklist of keys.
2. array_splice()
array_splice($b, 1, 1);
// (input array, starting position, number of elements to remove)
- This function is key-ignorant, it will target elements based on their position in the array. This is safe to use without checking for the existence of the position -- if missing, there will be no error.
array_splice()can remove a single element or, at best, remove multiple consecutive elements. If you need to remove non-consecutive elements you would need to make additional function calls.array_splice()does not require anarray_values()call because "Numerical keys in input are not preserved" -- this may or may not be desirable in certain situations.
3. array_filter() nested in array_values()
array_values(
array_filter(
$b,
function($k) {
return $k != 1;
},
ARRAY_FILTER_USE_KEY
)
)
- This technique relies on a custom function call and a flag to tell the filter to iterate only the keys.
- It will be a relatively poor performer because it will iterate all of the elements regardless of the logical necessity.
- It is the most verbose of the options that I will discuss.
- It further loses efficiency if you want to employ an
in_array()call with a whitelist/blacklist of keys in the custom function. - Prior to PHP7.4, passing a whitelist/blacklist/variable into the custom function scope will require the use of
use(). - It can be written as a one-liner.
- This is safe to use without checking for the existence of the index(es) -- if missing, there will be no error.
4. array_diff_key() nested in array_values()
array_values(
array_diff_key(
$b,
[1 => '']
)
);
- This technique isn't terribly verbose, but it is a bit of an overkill if you only need to remove one element.
array_diff_key()really shines when there is a whitelist/blacklist array of keys (which may have a varying element count). PHP is very swift at processing keys, so this function is very efficient at the task that it was designed to do.- The values in the array which is declared as the second parameter of
array_diff_key()are completely irrelevant -- they can benullor999or'eleventeen'-- only the keys are respected. array_diff_key()does not have any scoping challenges, compared toarray_filter(), because there is no custom function called.- It can be written as a one-liner.
- This is safe to use without checking for the existence of the index(es) -- if missing, there will be no error.
$out = array_diff_key($data, array_flip($bad_keys));
All I did was look through the list of Array functions until I found the one I needed (_diff_key).
The solution is indeed the one provided by Niet the Dark Absol. I would like to provide another similar solution for anyone who is after similar thing, but this one uses a whitelist instead of a blacklist:
$whitelist = array( 'good_key1', 'good_key2', ... );
$output = array_intersect_key( $data, array_flip( $whitelist ) );
Which will preserve keys from $whitelist array and remove the rest.
Main is not the element of array, its a part of a element of array
function array_cleanup( $array, $todelete )
{
$cloneArray = $array;
foreach( $cloneArray as $key => $value )
{
if (strpos($value, $todelete ) !== false)
unset( $array[ $key ] ); //$array[$key] = str_replace($toDelete, $replaceWith, $value) ; // add one more argument $replaceWith to function
}
return $array;
}
Edit:
with array
function array_cleanup( $array, $todelete )
{
foreach($todelete as $del){
$cloneArray = $array;
foreach( $cloneArray as $key => $value )
{
if (strpos($value, $del ) !== false)
unset( $array[ $key ] ); //$array[$key] = str_replace($toDelete, $replaceWith, $value) ; // add one more argument $replaceWith to function
}
}
return $array;
}
$newarray = array_cleanup( $cats, array('Category:Main') );
Wanted to note that while the accepted answer works there's a built in PHP function that handles this called array_filter. For this particular example it'd be something like:
public function arrayRemoveMain($var){
if ( strpos( $var, "Category:Main" ) !== false ) { return false; }
return true;
}
$newarray = array_filter( $cats, "arrayRemoveMain" );
Obviously there are many ways to do this, and the accepted answer may very well be the most ideal situation especially if there are a large number of $todelete options. With the built in array_filter I'm not aware of a way to pass additional parameters like $todelete so a new function would have to be created for each option.