I have array in PHP and I have problem with remove some elements from this array. It looks like this:
Array
(
[0] => 2x 633130A
[1] => 2x 525130B
[2] => 2x 591130B
[3] => 2x 963130B
[4] => 2x 813130B (20mm)
[5] => 2x 813130B
[6] => 2x 313130B (12mm)
[7] => 2x 313130B
[8] => 4x 413130B
[9] => 2x 633130B
[12] => 2x 381130A (23mm)
[13] => 2x 381130A
)
And now I'd like to remove this repeated elements without mm parameter as you can see below:
FROM =====> TO
Array Array
( (
[0] => 2x 633130A [0] => 2x 633130A
[1] => 2x 525130B [1] => 2x 525130B
[2] => 2x 591130B [2] => 2x 591130B
[3] => 2x 963130B [3] => 2x 963130B
[4] => 2x 813130B (20mm) [4] => 2x 813130B (20mm)
[5] => 2x 813130B <= REMOVE [5] => 2x 313130B (12mm)
[6] => 2x 313130B (12mm) [6] => 4x 413130B
[7] => 2x 313130B <= REMOVE [7] => 2x 633130B
[8] => 4x 413130B [8] => 2x 381130A (23mm)
[9] => 2x 633130B )
[12] => 2x 381130A (23mm)
[13] => 2x 381130A <= REMOVE
)
I tried array_unique doesn't work in this case, because elements are not exactly the same. Can anybody help me how to delete those repeated elements?
This will do what you need in this case:
foreach ($array as $value)
{
if (FALSE !== strpos($value, '('))
{
$string = trim(strtok($value, '('));
while (FALSE !== $key = array_search($string, $array))
{
unset($array[$key]);
}
}
}
It'll iterate over the array, find any elements that have a (
as part of the string, find any elements with a string that matches up to the (
(with extra white space trimmed), and then remove them if it finds it.
$initialData = array(
'2x 633130A',
'2x 525130B',
'2x 591130B',
'2x 963130B',
'2x 813130B (20mm)',
'2x 813130B',
'2x 313130B (12mm)',
'2x 313130B',
'4x 413130B',
'2x 633130B',
'2x 381130A (23mm)',
'2x 381130A',
);
$filteredArray = array_filter(
$initialData,
function($value) use ($initialData) {
if (strpos($value, 'mm') === FALSE) {
foreach($initialData as $testData) {
if (strlen($testData) > strlen($value) &&
substr($testData,0,strlen($value)) == $value) {
return FALSE;
}
}
}
return TRUE;
}
);
var_dump($filteredArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With