Make array value unique - php

this is the dynamic array. I'm trying to remove the repeated value and have only merged one. e.g. need to remove [0] => 1/2/48 & [1] => 1/2/48/56 and only have [2] => 1/2/48/56/58 .
Array(
[0] => 1/2/48
[1] => 1/2/48/56
[2] => 1/2/48/56/58
[3] => 1/2/245
[4] => 1/2/245/246
[5] => 1/2/265
)
So the array should look like
Array(
[0] => 1/2/48/56/58
[1] => 1/2/245/246
[2] => 1/2/265
)

One way to do it
$a = [
'1/2/48',
'1/2/48/56',
'1/2/48/56/58',
'1/2/245',
'1/2/245/246',
'1/2/265'
];
$result = array_values(
array_filter($a, function ($value, $index) use ($a) {
return !isset($a[$index + 1]) ||
strpos($a[$index + 1], $value) !== 0;
}, ARRAY_FILTER_USE_BOTH)
);
This assumes that your input array $a is sorted as you showed. Otherwise you'd need to sort it first.

if your php-version lt 5.6.0, and you haven't sort array like under
$a = [
'1/2/245/246',
'1/2/48',
'1/2/48/56',
'1/2/245',
'1/2/265',
'1/2/48/56/58'
];
you can try like this
$result = array_values(
array_filter($a, function ($value) use ($a) {
$is_exists = false;
foreach ($a as $v){
if (($v !== $value) && (strpos($v, $value) !== FALSE)){
$is_exists = true;
break;
}
}
return !$is_exists;
})
);

Related

PHP: search for values in the array and display the key

I have array with the structure as below.
Array
(
[example1] => Array
(
[0] => 'banana'
)
[example2] => Array
(
[0] => 'orange'
[1] => 'apple'
[2] => 'plum'
[3] => 'watermelon'
[4] => 'pumpkin'
)
[example3] => Array
(
[0] => 'cherry'
[1] => 'strawberry'
)
)
I am trying to display the key name for a sample value.
Eg.
looking for a value: 'apple' - result: 'example2'
Simply loop your arrays and check if element exists:
function search(string $search, array $source) {
foreach ($source as $key => $sub) {
if (in_array($search, $sub)) {
return $key;
}
}
}
search('apple', $source);
Just iterate thru all the subarrays and return the parent key.
$array = [
'example1' => ['banana'],
'example2' => ['orange', 'apple', 'plum', 'watermelon', 'pumpkin'],
'example3' => ['cherry', 'strawberry']
];
$needle = 'apple';
$result = '';
foreach($array as $parentKey => $child) {
if(in_array($needle, $child)) {
$result = $parentKey;
break;
}
}
echo $result;
example2
that's a good example too, thanks.
I built my function on this basis
function CheckArray($my_array,$search) {
$result = array_keys(array_filter($my_array, function ($arr) use ($search) {
return in_array($search, $arr);
}));
if(isset($result[0])){
return $result[0];
}else{
return "not find";
}
}

Filter certain folders from array

I have and array with paths to files, but I need to filter out certain folders.
This is just an example but I want to remove files that are in this case in folders like 'thumbs', 'database' & 'test'.
I could not find an array filter for this.
[
[0] => uploads/projects/pathtofile.jpg,
[1] => uploads/projects/thumbs/pathtofile.jpg,
[3] => uploads/database/projects/pathtofile.jpg,
[4] => uploads/projects/thumbs/database/pathtofile.jpg,
[5] => uploads/thumbs/projects/test/pathtofile.jpg
]
You can use array_interset()
foreach($array as $key=> $ar){
if(count(array_intersect(explode('/',$ar),['thumbs', 'database','test']))>0){
unset($array[$key]);
}
}
Output:- https://eval.in/939916
I'd go with array_filter() and preg_match():
$filtered = array_filter($a, function($i) {
return preg_match('/(thumbs|database|test)/', $i) !== 1;
});
If your file path starts with / then this would work fine:
$blacklist = ['/thumb/', '/image/'];
$files = ['/dir/thumb/image.jpg', '/dir/image/thumb.jpg', '/dir/subdir/file.php'];
$filtered_files = array_filter($files, function($value) use($blacklist){
foreach($blacklist as $blk){
if(strpos($value, $blk) !== false){
return false;
}
}
return true;
});
print_r($filtered_files);
Output :
Array
(
[2] => /dir/subdir/file.php
)
What about using array_filter callable?
<?php
$a = array(
0 => 'uploads/projects/pathtofile.jpg',
1 => 'uploads/projects/thumbs/pathtofile.jpg',
3 => 'uploads/database/projects/pathtofile.jpg',
4 => 'uploads/projects/thumbs/database/pathtofile.jpg',
5 => 'uploads/thumbs/projects/test/pathtofile.jpg',
6 => 'uploads/thumb/projects/pathtofile.jpg'
);
$b = array_values(array_filter($a, function ($item) {
return !preg_match('/(\/thumbs\/|\/database\/|\/test\/)/', $item);
}));
echo '<pre>' . print_r($b, 1) . '</pre>';
Output:
Array
(
[0] => uploads/projects/pathtofile.jpg
[1] => uploads/thumb/projects/pathtofile.jpg
)

How can I compare two Arrays and detect if the values are incorrect or missing?

I have to arrays I would like to compare:
$original and $duplicate.
for example here is my original file:
print_r($original);
Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 )
and here is my duplicate:
print_r($dublicate);
Array ( [0] => cat423 [1] => dug356 )
I compare them with array_diff:
$result = array_diff($original, $dublicate);
My result:
Array ( [1] => dog456 [2] => horse872 [3] => duck082 )
So far so good, but I need to make a difference between the values which are incorrect and the values which are completely missing. Is this possible?
A way would be to crawl the entire original array, afterwards you will have two arrays, missings and duplicates.
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
$missings = $duplicates = array();
foreach ($original as $val) {
if (in_array($val, $duplicate))
$duplicates[] = $val;
else
$missings[] = $val;
}
If you need the keys as well, you would have to alter the foreach loop like so:
foreach ($original as $key=>$val) {
if (in_array($val, $duplicate))
$duplicates[] = array("key" => $key, "value" => $val);
else
$missings[] = array("key" => $key, "value" => $val);
}
use in_array function
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
foreach ($original as $item) {
if(in_array($item, $duplicate))
{
$dup[] = $item;
}
else
{
$miss[] = $item;
}
}
print_r($miss); #Array ( [0] => dog456 [1] => horse872 [2] => duck082 )
print_r($dup); #Array ( [0] => cat423 )
Working Preview

Get array that contain a value provided in PHP

I have this array:
Array
(
[0] => CMS_ADMIN
[1] => CMS_ACADEMIC
[2] => CMS_FINANCE
[3] => HRM_HR
[4] => SRM_D
[5] => SRM_CNC
[6] => SRM_TM
[7] => SRM_DE
)
I would like to get the array by searching to the array value using the word provided. Let say I'm just provide the 'CMS' word, so how i'm gonna get the [0] => CMS_ADMIN, [1] =>CMS_ACADEMIC, [2] => CMS_FINANCE assign to the new array. Please help....
With a function that looks like this:
function array_filter_prefix($array, $prefix) {
$result = array();
foreach ($array as $value) {
if (strpos($value, $prefix) === 0) {
$result[] = $value;
}
}
return $result;
}
Given an input array, $test, you can then do this to get the result:
$result = array_filter_prefix($test, 'CMS');
print_r($result);
Codepad here.
batter style in PHP 5.3
$prefix = "CMS";
$new = array_filter($array, function ($str) use ($prefix) {
return (strpos($str, $prefix) === 0);
});

Sort array by key value

So I have this array.
Array
(
[0] => Array
(
[key_1] => something
[type] => first_type
)
[1] => Array
(
[key_1] => something_else
[type] => first_type
)
[2] => Array
(
[key_1] => something_else_3
[type] => second_type
)
[3] => Array
(
[key_1] => something_else_4
[type] => second_type
)
)
I have to sort by type value in a pattern like this:
first_type
second_type
first_type
second_type
My questions is, how can I do this?
Thanks a lot!
You need to use usort with a custom comparison function that compares the key_1 sub-keys of each item (you can use strcmp to do this conveniently). Assuming you do not want to change the structure of the resulting array, it would look something like this:
$arr = /* your array */
usort($arr, function($a, $b) { return strcmp($a['key_1'], $b['key_1']); });
So here's how I got it to work:
function filter_by_value($array, $index, $value) {
if(is_array($array) && count($array) > 0) {
foreach(array_keys($array) as $key){
$temp[$key] = $array[$key][$index];
if ($temp[$key] == $value){
$newarray[$key] = $array[$key];
}
}
}
return $newarray;
}
$array = /* array here */
$type1 = array_values(filter_by_value($array, 'type', '1'));
$type2 = array_values(filter_by_value($array, 'type', '2'));
$i = 1; $x = 1; $y = 1;
$sorted = array();
foreach ($array as $a) {
if ($i % 2) {
$sorted[$i-1] = $type1[$x-1];
$x++;
} else {
$sorted[$i-1] = $type2[$y-1];
$y++;
}
$i++;
}
Found filter_by_value() on php.net but I don't remember where so, that's not made by me.
Maybe this is not the best solution but it works pretty fine.
If sort() and its relevant alternatives don't work you will have to use usort() or uasort() with a custom function to sort this array.

Categories