PHP. Removing part of the array - php

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

Related

array_splice() is not working as expected

Some help please with this thing that was confused me about the correct use of array_splice();
When i copy literally the following code from the php.net website, that appears as follow:
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")
But on my localhost, the result is not as shown in the website example. I got this:
Array ( [0] => blue [1] => yellow )
What happens here?
Resource http://php.net/manual/en/function.array-splice.php
This is correct. The return array will contain removed elements, i.e. ( "red", "green" ). The original array will be modified to contain the elements which were not removed, i.e. ( "blue", "yellow" ).

Array Diff Confusion

Upon trying this code, I am confused why the value yellow is not displayed.
Can someone elaborate this, please ?
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
Multiple occurrences in $array1 are all treated the same way. This will output :
Array
(
[1] => blue
)
From documentation:
array array_diff ( array $array1 , array $array2 [, array $... ] )
Returns an array containing all the entries from array1 that are not
present in any of the other arrays.
According to this, what follows will print blue because it is the only element that does not exist in $array2.
It will not print yellow because it checks for the elements that are present in $array1 but not in $array2, NOT vice versa:
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
Only blue from $array1 does not exist in $array2, so print it. Do not care about the elements that are present in $array2 but not in $array1, so yellow won't be displayed.
this happens because you are searching for the difference between the first and second array, which is just blue, because blue is not contained by the second array.
if you try this:
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array2, $array1);
print_r($result);
?>
the output will be Array ( [0] => yellow) because this is the difference between the second and first array.
Hope this helps! :D
Becouse this is how array_diff works:
Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.
http://php.net/manual/en/function.array-diff.php
According to PHP Manual : http://fr2.php.net/manual/en/function.array-diff.php
array_diff Returns an array containing all the entries from the first array that are not present in any of the other arrays.
The definition of
array_diff($array1, $array2);
is to return entries in array1 that are not present in other arrays.
You could do
$result2 = array_diff($array2, $array1);
and then merge $result1 and $result2 if you want to see what's missing in either one.
Did you read the documentation?
Compares array1 against one or more other arrays and returns the
values in array1 that are not present in any of the other arrays.
The only value in array1 which is not present in array2 is "blue".
Same thing confused me long time ago :)
You should swap array in array_diff in your case.
Arrray diff actually works: show me what i have in first array ($array1) that i don't have in other arrays
Cheers! :)
The output is correct because the function displays the values that are present in the first array but not in the second one. If you want to display yellow then you have to invert the positions of the arrays in your function. Hope it helps.

Check if Array has identical Entries

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
)

Pushing random array elements into another array in PHP

I have an array consisting of N>10 URLs. I want to randomly pick 10 of them and store them in another array. How can I achieve this? Is array_rand() the way to go? If yes, then how do I ensure that there are no duplicities in the output array? Do I have to check the second array everytime a new element is added for existence?
// $firstArray is defined earlier
$secondArray = array();
array_push(array_rand($firstArray, 10));
This doesn't work unfortunately. I was thinking about using a for cycle for the array_push() but I was just curious if array_rand() can do that for me.
Thanks for advice!
array_rand returns keys so
$randKeys = array_rand($firstArray, 10);
foreach($randKeys as $key)
$secondArray[] = $firstArray[$key]
This can be done without array_rand(). Use shuffle() to shuffle the array elements and then use array_slice() to get the first 10 items:
$secondArray = array();
shuffle($firstArray);
$secondArray = array_slice($firstArray, 0, 10);
Demo!
As people said there is a second argument in array_rand() to pick how many random elements you want, always remember to read the Manual
//Lets pick 10 mammals
$mammals = array('dog', 'cat', 'pig', 'horse', 'bat', 'mouse', 'platypus', 'bear', 'donkey', 'deer', 'hog', 'duck');
$ten = array_rand(array_flip($mammals), 10);
//If what yo u really wanted is to append them to another array, let's say "animals":
$animals = array('fish', 'crab', 'whale', 'eagle');
$animals = array_merge($animals, array_rand(array_flip($mammals), 10));
Explanation
array_rand() will return you the keys, so we can use array_flip() here to reverse the keys => values positions before picking them, no need to loop through them again.
And using array_merge() we merge them together, with no need to loop through the ten random elements to add them one by one, unless ... you want a specific order or other logic.
Not very optimized solution, but for small amounts of data it may suit:
$firstArray = array(1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9);
$secondArray = array();
$tmp = array_unique($firstArray);
shuffle($tmp);
$secondArray += array_slice($tmp,0, 10);
If you use array_push like in the example code, the last index in your second array will contain the returned 10 indexes
Eg.
$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => d
[1] => e
[2] => f
)
)
I would use a while in this case and pick only one value at a time. Something like:
$stack = array();
while(count($stack)<10){
$item = array_rand($collection_of_urls);
if(!in_array($item)
array_push($stack, $item);
}
this simple
$rand_keys = array_rand($input, 10);
print_r($rand_keys);

Deleting a specific item by using array_splice/array_slice in PHP

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'));

Categories