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
)
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 have two arrays
1st array
first array containts 60 strings like this:
['string1','string2', ... , string60];
2nd array
And I have an associative array like this:
['Key' => value, ..., 'Key' => value]
What I need to do is compare each value from first array(that contains 60 ellements), with each key from the second array, and if second(associative) array doesn't contain key that matches any value from first array - I should add such ellement to the associative array.
For example second array doesn't have key that matches string5 for example, and I'm not talking about value of the key, I'm literally talking about Key itself. So now I need to add string5 as a new key => value ellement to the array, the Key must be the word string5, and the value must be empty.
What is the best way to do it?
Not more complicated than:
$combined = $array2 + array_fill_keys($array1, null);
array_fill_keys creates an array like ['string1' => null, ..], + adds all of these keys which don't already exists in $array2.
$combined = $array2 + array_fill_keys($array1, null);// key value will be maintained
array_values($array2); //index starts from 0
This should work
foreach($array_1 as $val) {
if(!isset($array_2[$val])) {
$array_2[$val] = null;
}
}
pretty sure there are people who know more efficient ways (resource wise) as this might take long when you have huge arrays.
Here is the logical way to do this.
First divide the second array in key and values array. I mean two different array.
So
$keys = array_keys($array2);
$values = array_values($array2);
now you have to take the different from $array1 to $array2 sigular or vice-versa ( Depends on your requirement ) and it will give you the difference of missing keys.
$diff = array_diff($array1,$keys);
Now you will be able to find it easily.
Please refer to array_diff Source: php.net
<?php
$required = array('key1', 'key2', 'key3','key4');
$data = array(
'key1' => 10,
'key2' => 20
);
$arrayDiff = array_diff_key(array_flip($required),$data);
$final = array_merge($data,$arrayDiff);
// Result
// Array
//(
// [key1] => 10
// [key2] => 20
// [key3] => 2
// [key4] => 3
//)
?>
If you want default value to be populated to the new keys added to the array, add below line before merge and use the variable $arrayFill instead of $arrayDiff in the merge statement
$arrayFill = array_fill_keys(array_flip($arrayDiff),0);
I am checking the array_unique function. The manual says that it will also sort the values. But I cannot see that it is sorting the values. Please see my sample code.
$input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red");
print_r($input);
$result = array_unique($input,SORT_STRING);
print_r($result);
The output is
Array
(
[a] => green
[3] => red
[b] => green
[1] => blue
[4] => red
)
Array
(
[a] => green
[3] => red
[1] => blue
)
Here the array $result is not sorted. Any help is appreciated.
Thank you
Pramod
array_unique:
Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() keeps the first key encountered for every value, and ignore all following keys.
you can try this to get the result:
<?php
$input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red");
print_r($input);
$result = array_unique($input);
print_r($result);
asort($result);
print_r($result);
The manual does not say it will sort the array elements, it says that the sort_flags parameters modifies the sorting behavior.
The optional second parameter sort_flags may be used to modify the
sorting behavior using these values: [...]
The sorting behavior is used to sort the array values in order to perform the comparison and determine whether one element is considered to be equal to another. It does not modify the order of the underlying array.
If you want to sort your array, you'll have to do that as a separate operation. Documentation on array sorting can be found here.
For a default ascending sort based on the array's values, you could use asort.
array_unique takes an input array and returns a new array without duplicate values. It doesn't sort actually. Read more at http://php.net/manual/en/function.array-unique.php
I am beginner in PHP programming. I want to know how to define single and multidimensional array in PHP.
There are a wide variety of ways to do this, all of which are well explained on the relevant PHP manual page.
However, in terms of some examples:
$singleArray = array(1, 2, 3);
$multiArray = array(array(1, 2, 3), array(4, 5, 6));
You of course can also use the following syntax:
$singleArray = $multiArray = array();
$singleArray[] = 1;
$singleArray[] = 2;
...
$multiArray[0][] = "Bob";
$multiArray[0][] = "Steve";
$multiArray[1][] = "Dave";
$multiArray[1][] = "Jack";
...
You can also provide you own keys (in addition to the numeric ones), such as:
$singleArray = array('first'=>1, 'second'=>2, 'third'=>3);
(Use array_keys to extract the keys from such an array.)
However, if you're just starting out, you really want to spend a bit of time reading the excellent online documentation, practising with the tutorials, etc. as this will be a lot faster that asking a multitude of questions on SO. :-)
Array elements in PHP can hold values of any type, such as numbers, strings and objects. They can also hold other arrays, which means you can create multidimensional, or nested, arrays.
Single dimensional Array :
$myArray = array(value1, value2, value3);
Multidimensional Array :
$myArray = array(
array( value1, value2, value3 ),
array( value4, value5, value6 ),
array( value7, value8, value9 )
);
Here, the top-level array contains 3 elements. Each element is itself an array containing 3 values.
Basically, there are three different types of arrays:
Numeric array – An array with a numeric ID key.
Multidimensional arrays – An array containing one or more arrays.
Associative arrays – An array where each ID key is associated with a value.
Read here for more about these types : Types of Arrays in PHP
Did you read the manual ?
Especially the exemples, like this one :
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
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'));