How do I delete a specific item by using array_splice/array_slice in PHP?
for example:
array('a','b','c');
how to just delete 'b'?
so the array remains:
array('a','c');
Thanks
Actually. I came up with two ways to do that. It depends on how you are going to handle with the index issue.
If you want to remain the indices after deleting certain elements from an array, you would need unset().
<?php
$array = array("Tom","Jack","Rick","Alex"); //the original array
/*Here, I am gonna delete "Rick" only but remain the indices for the rest */
unset($array[2]);
print_r($array);
?>
The out put would be:
Array ( [0] => Tom [1] => Jack [3] => Alex ) //The indices do not change!
However, if you need a new array without keeping the previous indices, then use array_splice():
<?php
$array = array("Tom","Jack","Rick","Alex"); //the original array
/*Here,we delete "Rick" but change indices at the same time*/
array_splice($array,2,1); // use array_splice()
print_r($array);
?>
The output this time would be:
Array ( [0] => Tom [1] => Jack [2] => Alex )
Hope, this would help!
how to just delete "blue"?
Here you go:
$input = array("red", "green", "blue", "yellow");
array_splice($input, array_search('blue', $input), 1);
Basically: Just do it.
The manual has good examples like this one:
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")
if something doesn't work out for you, please add more detail to your question.
Starting with (id is the item you want to delete):
$input = array("a", "b", "c", "d", "e");
$id=2;
array splice:
$a1 = array_slice($input, $id);
print_r($a1);
Array
(
[0] => c
[1] => d
[2] => e
)
array slice:
array_splice($input, $id-1);
print_r($input);
Array
(
[0] => a
)
Merging the splice and the slice will give you an array that is the same as the input array but without the specific item.
You probably can do this using only one line but I'll leave that as an exercise for the readers.
Does it have to be array_splice? I think the most appropriate way (maybe depending on the array size, I don't know how well array_search scales) is to use array_search() with unset():
$array = array('foo', 'bar' => 'baz', 'bla', 5 => 'blubb');
// want to delete 'baz'
if(($key = array_search('baz', $array)) !== FALSE) {
unset($array[$key]);
}
Use array_diff:
$array = array_diff($array , array('blue'));
Related
Imagine that you have this PHP code:$array1 = array("henk", "jackson", "henk");.
Is there a way to check if $array1 has two of the same values in it (in this case henk) and then make it delete one of them so one stays in the array?
All you need is array_unique():
$array1 = array("henk", "jackson", "henk");
$array2 = array_unique($array1);
print_r($array2);
Result:
Array
(
[0] => henk
[1] => jackson
)
I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.
I have two arrays
$original = array(
array('fruit' => 'appel','color' => 'green'),
array('fruit' => 'Banana','color' => 'Yellow'),
array('fruit' => 'orange','color' => 'orange',)
);
and
$new = array(
array('fruit' => 'appel'),
array('fruit' => 'orange')
);
Now i want to compare the two arrays and print out the different one.
In this case i want to keep
array('fruit' => 'Banana','color' => 'Yellow')
When i use array_intersect_key
$original_new = array_intersect_key($new, $original);
it's deleting the array i want to keep.
I thought i do this:
$original_new = array_intersect_key($new, $original);
$original_new = array_diff($original_new, $original);
But this is of course not working.
Can somebody help me out whit this?
Using some loop and array. Check Online.
First make the array from $new array with the column only, and using the foreach loop over the $original array just check the fruit is in the $new array or not, if not than store the complete sub array in an array name $arr.
$arr = array();
$com = array_column($new, 'fruit');
foreach($original as $value){
if(!in_array($value['fruit'], $com)){
$arr[] = $value;
}
}
print_r($arr); //Array ( [0] => Array ( [fruit] => Banana [color] => Yellow ) )
Just to provide a different point of view,
You can get the solution using some array functions
you just need to get array_column fruit of $new array and same of $original array, get the array_diff of the 2 arrays, finally get the key ,
just try this:
$res = $original[key(array_diff(
array_column($original,'fruit'), array_column($new,'fruit')))];
You can do it without writing own code:
$res = array_intersect_key($original,
array_diff(array_column($original, 'fruit'),
array_column($new, 'fruit')));
demo
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"2.00");
$a2=array("a"=>"red","b"=>"green","c"=>"2");
$r = array_diff_assoc($a1, $a2);
print_r($r);
You can use array_diff_assoc (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
But note that the comparison is strict (===)
The result for the code above:
Array
(
[c] => 2.00
)
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
array_diff β Computes the difference of arrays
Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
print_r($result);
This will return
Array ( [d] => yellow )
I got an array, with alot of entries, like:
$array = ['abc', 'def', 'ghi', 'abc'];
Now I wanna check, if there are identical entries in this array.
For example there is 'abc' twice in this array.
When I found identical entries, I wanna filter them out.
Whats the best way to do that without MySQL?
I could just check
if($array[0] == $array[1])
etc
but that would be horrible amount of work, and some bad programming i guess.
Greetings
You can just use array_unqique: http://www.php.net/manual/en/function.array-unique.php
Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
The above example will output:
Array
(
[a] => green
[0] => red
[1] => blue
)
It is necessary to remove part of the array. Here is an example of an array:
Array ( [0] => one [1] => two [2] => three [3] => four [4] => five )
The variable can be based on one of the following values ββin the array.
Suggests there is 'three'. Need to take one, two and everything else removed.
Is there any standard methods, or a good solution that would not need to use a loop?
You can use array_splice for that
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")
If you don't want to use a loop, you could use array_splice.
$input = array("red", "green", "blue", "yellow");
array_splice($input, $varaible, -1);
// $input is now array("red", "yellow")
This will use #JeroenMoons array_splice but will do the array_search I suggested too
function reduce_my_array($array, $value)
{
// look for location of $value in $array
$offset=array_search($value, $array);
// if not found return original
if($offset===false) return $array;
// remove from the found offset to the end of the array
return array_splice($array, $offset+1);
}
Note:
array_search returns the INDEX which can be 0
array_splice uses number of entries as the offset
so for your example with numerical indexes 0 to ... you need to tell array splice index+1