I have an sorted array which contains first names of people.
This array has lots of names which are same.
I want to output only duplicate names.
Example,
input array:
Array
(
[0] => Abbas
[1] => Abhay
[2] => Abhinav
[3] => Abhishek
[4] => Aditya
[5] => Ahmed
[6] => Ahmed
[7] => Ajay
[8] => Ajay
}
It should return
Array
(
[5] => Ahmed
[6] => Ahmed
[7] => Ajay
[8] => Ajay
}
Use this code:
# assuming your original array is $arr
array_unique(array_diff_assoc($arr, array_unique($arr)));
It will return unique duplicates but if you want non-unique duplicates then use:
array_diff_assoc($arr, array_unique($arr));
EDIT: Based on your comments, try this code:
$uarr = array_unique($arr);
var_dump(array_diff($arr, array_diff($uarr, array_diff_assoc($arr, $uarr))));
OUTPUT
array(4) {
[5]=>
string(5) "Ahmed"
[6]=>
string(5) "Ahmed"
[7]=>
string(4) "Ajay"
[8]=>
string(4) "Ajay"
}
You could use this function http://php.net/manual/en/function.array-unique.php to get an array withoutt he duplicate values, then you can use this function http://www.php.net/manual/en/function.array-intersect.php to find the differences, maintaining key association.
Try array_reduce:
http://php.net/manual/en/function.array-reduce.php
Create a callback that populates an array using the values from $input as keys, and increments them accordingly. And then filter those that appear more than once.
Using array_count_values() to count up everything in the array, then filter the resulting array to show only the ones where there's more than 1:
$input = array(.... your names here ....);
$counts = array_count_values($input);
$duplicates = array_filter($counts, function element { return ($element > 1) });
Doing that off the top of my head, but should be enough to get you started.
Related
My array looks like:
{flower},{animals},{food},{people},{trees}
I want to explode with {, , & }.
My output should contain only words inside curly brackets.
My code:
$array = explode("},{", $list);
After execution of this code $array will be
$array = Array (
[0] => {flower
[1] => animals
[2] => food
[3] => people
[4] => trees}
)
But output array should be:
$array = Array (
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
Can anyone please tell me how can I modify my code to get this array?
I would go for preg_split like below
<?php
$list = "{flower},{animals},{food},{people},{trees}";
$array = preg_split('/[},{]/', $list, 0, PREG_SPLIT_NO_EMPTY);
print_r($array);
?>
The output is
Array
(
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
You could try to extract the words using a RegEx instead of splitting the string:
$list = "{flower},{animals},{food},{people},{trees}";
// Match anything between curly brackets
// The "U" flag prevents the regex to make a single match with the first and last brackets
preg_match_all('~{(.+)}~U', $list, $result);
// Only keep the 1st capturing group
$words = $result[1];
var_dump($words);
Output:
array(5) {
[0]=>
string(6) "flower"
[1]=>
string(7) "animals"
[2]=>
string(4) "food"
[3]=>
string(6) "people"
[4]=>
string(5) "trees"
}
Array ( [0] => UK [1] => France [2] => USA ) in these array get only values
like array(UK, France, USA) am trying like below,
$expression=array_values(array('0' => 'UK', '1' => 'France', '2' => 'USA'));
var_dump($expression);
OUTPUT PLAN:
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
Can i get my desired output?
Please read answer carefully.
$arr = array('UK', 'France', 'USA'); // It has 0 ,1 ,2 keys but you cannot see in the code`
But in browser you can see it.
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
Just use loop to print each country
foreach($arr as $country){
echo $country."<br>";
}
You can understand it by below loop
foreach($arr as $k=>$country){
echo "$k => $country"."<br>"; // Here $k is key like 0,1,2..
}
If you have array like below:-
$arr = array('uk'=>'UK', 'france'=>'France', 'usa'=>'USA') // It has uk ,france ,usa keys
now array_values($arr) will give you output as below
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
It will remove all keys and regenerate index of key from 0.
Refer below links to understand PHP array:-
Link1
Link2
Link3
Hope it will help you :)
You could just do:
$out = array();
foreach($old_array as $new_value) { //Where $old_array is the array you want to convert
array_push($out, $new_value);
}
All PHP arrays have an internal index whether you attach one or not. So in your example even if you created an array using $countries = array("USA", "UK", "France") it would still output with indexes.
You can however ignore the indexes when your looping through it and only work with the values using a foreach() loop.
An example of such a loop would be...
foreach($expression as $index => $country) {
echo($country . "<br />");
};
The above example will print each country on its own line. You can adapt it to suit whatever looping you need.
As a side note be aware that the index will commence from 0 so item 1 in the array will have an index of 0 and increment from there.
You have this array.
Array ( [0] => UK [1] => France [2] => USA )
you have key and value assigned to it.
if you make another array like
array('UK','France','USA')
It is an associative array. Its the same as above.
Read it for more info
If you want to do operation with the array you can use foreach and for or other array related functions. So, first of all say what are you trying to accomplish with this one.
$expression=array_values(array('0' => 'UK', '1' => 'France', '2' => 'USA'));
foreach($expression as $val) {
echo $val.",";
}
I am trying to compare a sub-array with the indices with a main array. I tried using array_diff, array_intersect_key, etc, but unable to find the way to proceed, other than using a stupid for loop and doing some old school method.
Okay, let me clarify my question. Say, I have two arrays:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] => W
[6] => o
[7] => r
[8] => l
[9] => d
[10] => !
)
Array
(
[1] => e
[5] => W
[7] => r
[10] => !
)
The first one is the main array of full string: HelloWorld! and the second one is the sub-array, which has some selected indices and it's values, given by the users. This can also be wrong, for eg:
Array
(
[1] => F
[5] => a
[7] => 6
[10] => t
)
Now, when I pass the first array, it should obviously return true and the next one should return false. Is this possible with the built-in functions using PHP? Thanks in advance.
You should use array_intersect_assoc() if you want to check also if the keys match
if (array_intersect_assoc ($a,$b)==$b) {} else {}
given that $a is the full array and $b the subset to test against.
I think array_intersect_uassoc() is the function you're looking for. It compares based on both keys and values. Here's a quick example:
$array1 = array(0 => 'h', 1 => 'e', 2 => 'l', 3 => 'o');
$array2 = array(0 => 'h', 1 => 'e');
$array3 = array(0 => 'h', 1 => 'z');
var_dump(array_intersect_uassoc($array1, $array2, 'strcasecmp'));
var_dump(array_intersect_uassoc($array1, $array3, 'strcasecmp'));
Output:
array(2) {
[0]=>
string(1) "h"
[1]=>
string(1) "e"
}
array(1) {
[0]=>
string(1) "h"
}
You then compare the size of the second array with the size of the returned array - if they are equal, all matches are right. If the returned array is smaller - there's a mistake in the second array.
Replace strcasecmp() with a callback to your liking and profit :)
Cheers
$array3 = array_diff($array2,$array1); //array2 is checking either present or not in array1
and check array3 is empty. if array3 is empty then matched and if not empty than does not matched.
if (array_diff_assoc($array2, $array1)) {
echo 'array 2 is not an exact subset of array 1';
}
array_diff_assoc returns all elements from $array2 which are not in $array1. So if array 2 is a subset of array 1, the return is an empty array, which evaluates to false, and otherwise a non-empty array, which evaluates to true.
The answer on this question, pointed me in a possible direction, but it processes the string once, then loops through the result. Is there a way to do it in one process?
My string is like this, but much longer:
954_adhesives
7_air fresheners
25_albums
236_stuffed_animial
819_antenna toppers
69_appliances
47_aprons
28_armbands
I'd like to split it on linebreaks, then on underscore so that the number before the underscore is the key and the phrase after the underscore is the value.
Just use a regular expression and array_combine:
preg_match_all('/^([0-9]+)_(.*)$/m', $input, $matches);
$result = array_combine($matches[1], array_map('trim', $matches[2]));
Sample output:
array(8) {
[954]=>
string(9) "adhesives"
[7]=>
string(14) "air fresheners"
[25]=>
string(6) "albums"
[236]=>
string(15) "stuffed_animial"
[819]=>
string(15) "antenna toppers"
[69]=>
string(10) "appliances"
[47]=>
string(6) "aprons"
[28]=>
string(8) "armbands"
}
Use ksort or arsort if you need the result sorted as well, by keys or values respectively.
You can do it in one line:
$result = preg_split('_|\n',$string);
Here is a handy-dandy tester: http://www.fullonrobotchubby.co.uk/random/preg_tester/preg_tester.php
EDIT:
For posterity, here's my solution. However, #Niels Keurentjes answer is more appropriate, as it matches a number at the beginning.
If you wanted to do this with regular expressions, you could do something like:
preg_match_all("/^(.*?)_(.*)$/m", $content, $matches);
Should do the trick.
If you want the result to be a nested array like this;
Array
(
[0] => Array
(
[0] => 954
[1] => adhesives
)
[1] => Array
(
[0] => 7
[1] => air fresheners
)
[2] => Array
(
[0] => 25
[1] => albums
)
)
then you could use an array_map eg;
$str =
"954_adhesives
7_air fresheners
25_albums";
$arr = array_map(
function($s) {return explode('_', $s);},
explode("\n", $str)
);
print_r($arr);
I've just used the first three lines of your string for brevity but the same function works ok on the whole string.
I've two arrays array1 and array2 and I want to add all elements of array2 to the end of array1. array1 contains many items.
The keys are numeric and I don't want this syntax:
array1 = array1 + array2
or
array1 = SomeArrayFun(array1,array2)
As it takes away CPU times ( as array is created twice )
What I want is:
array1 . SomeAddFun(array2); // This will not create any new arrays
Is there any way to do it?
If you'd like to append data to an existing array you should se array_splice.
With the proper arguments you'll be able to insert/append the contents of $array2 into $array1, as in the below example.
$array1 = array (1,2,3);
$array2 = array (4,5,6);
array_splice ($array1, count ($array1), 0, $array2);
print_r ($array1);
output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
You might use ArrayObject with the append function:
$arrayobj = new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
Result:
object(ArrayObject)#1 (5) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
[2]=>
string(5) "third"
[3]=>
string(6) "fourth"
}
Don't know for appending arrays though, as they seem to be appended as a "subarray" and not as part of the whole.
Docs: http://www.php.net/manual/en/arrayobject.append.php