check if value explode in array is duplicated with another explode value - php

hello try to find the duplicated value in array i have array like that
$array = array('1%2','3%4','1%2',1%3);
so i want to find duplicated 2 after % so i used explode inside foreach
foreach($array as $value){
$s = explode('%',$value);
if($s[1] == $s[1]){
echo 'there are duplicated 2';
}
}
so i want $s[1] check if value after % in array is duplicated
is there anyway to do that

You will need to collect the right side values as you loop through them and check for duplicates. I am accessing the strings' right side values via their "offset" [2]. When found, you can exit the loop with a break.
Code: (Demo)
$array=['1%2','3%4','1%2','1%3'];
$kept=[];
foreach($array as $i=>$v){
if(in_array($v[2],$kept)){
echo "Element (index $i) containing $v has duplicate right side value.";
break;
}
$kept[]=$v[2];
}
Output:
Element (index 2) containing 1%2 has duplicate right side value.
If you want to search for all element that end with %2, you can use preg_grep().
Code:
$search=2;
$array=['1%2','1%3','1%4','3%2','5%2'];
var_export(preg_grep("/%{$search}$/",$array));
Output:
array (
0 => '1%2',
3 => '3%2',
4 => '5%2',
)
Or without regex, it will require more function calls:
$search=2;
$array=['21%2','1%3','2%22','1%4','3%21','5%2'];
var_export(array_filter($array,function($v)use($search){return strpos($v,"%$search")+2===strlen($v);}));
Output:
array (
0 => '21%2',
5 => '5%2',
)
...[deep breath] Here is attempted answer #4...
Code:
$array=['1%2','1%3','1%4','3%2','5%2'];
foreach($array as $v){
$grouped[explode('%',$v)[1]][]=$v; // use right side number as key
}
var_export($grouped);
Output:
array (
2 =>
array (
0 => '1%2',
1 => '3%2',
2 => '5%2',
),
3 =>
array (
0 => '1%3',
),
4 =>
array (
0 => '1%4',
),
)
If you want to count the right side values in the array:
$array=['1%2','1%3','1%4','3%2','5%2'];
$array=preg_replace('/\d+%/','',$array); // strip the left-size and % from elements
var_export(array_count_values($array)); // count occurrences
Output:
// [right side values] => [counts]
array (
2 => 3,
3 => 1,
4 => 1,
)

Related

print the array when it is exploded

In the below code i am getting the output
Array ( [0] => 1 [1] => 2 )
but the expected output is
Array ( [0] => 1 [1] => 2 [2] => 3) Array ( [0] => 1 [1] => 2 )
why is it always executing the second if condition? although the first condition is also true.
this is the code I have tried
<?php
$test_arr=array();
$temp_option_arr=array();
$option_arr=array();
$options_array_val = Array ( 0 => "animals:1", 1 => "animals:2", 2 => "animals:3", 3 => "birds:1", 4 => "birds:2" );
foreach($options_array_val as $options_val)
{
$search_filter = explode(":", $options_val);
print_r($search_filter);
if(!in_array($search_filter[0],$option_arr))
{
array_push($temp_option_arr,$search_filter[1]);
array_push($option_arr,$search_filter[0]);
$temp_option_arr=array();
}
array_push($temp_option_arr,$search_filter[1]);
}
$test_arr[$search_filter[0]]=$temp_option_arr;
$find_species = array();
if(!empty($test_arr['animals']))
{
$find_species = $test_arr['animals'];
print_r($find_species);
}
if(!empty($test_arr['birds']))
{
$find_species = $test_arr['birds'];
print_r($find_species);
}
?>
The line
$test_arr[$search_filter[0]]=$temp_option_arr;
is out of the foreach scope, therefore it only sets the array for the birds and not for the animals, so you need to move it one line upper.
Also, you assign temp_option_arr to a value
array_push($temp_option_arr,$search_filter[1]);
then set it back to empty array without using it
$temp_option_arr=array();
You can remove the first one I guess
You clear $temp_option_arr in the first part of your code, so it will have nothing that concerns animals by the time you exit the first loop.
But instead of using all these different arrays, just build an associative array keyed by the species (animals, birds, ...), and with as values the arrays of IDs (1, 2, 3, ... i.e., the parts after the :):
foreach($options_array_val as $options_val) {
list($species, $id) = explode(":", $options_val);
$option_arr[$species][] = $id;
}
After this loop the structure of $option_arr is this:
Array (
"animals" => Array (1, 2, 3)
"birds" => Array (1, 2)
)
I think you can do what you want with that. For instance to only get the animals:
$option_arr["animals"]
which is:
Array (1, 2, 3)

How can I get all array elements, where the value only occurs once in the array?

I'm trying to get all array elements, where the value only occurs once in the array.
I tried to use:
array_unique($array);
But this does only remove the duplicates, which is not what I want.
As an example:
$array = 0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
5 => 2
6 => 3
7 => 4
8 => 5
Expected output:
array(
0=>1
)
As you can see only the value 1 occurs once in the array, all other values are more than once in the array. So I only want to keep that one element.
This should work for you:
First use array_count_values() to count how many times each value is in your array. This will return something like this:
Array (
[1] => 1
[2] => 2
[3] => 2
[4] => 2
[5] => 2
// ↑ ↑
// Value Amount
)
After that you can use array_filter() to only get the values, which occurs once in your array. Means:
Array (
[1] => 1
[2] => 2
[3] => 2
[4] => 2
[5] => 2
)
And at the end simply use array_keys() to get the value from the original array.
Code:
<?php
$arr = [1,2,3,4,5,2,3,4,5];
$result = array_keys(array_filter(array_count_values($arr), function($v){
return $v == 1;
}));
print_r($result);
?>
output:
Array (
[0] => 1
)
You can use array_count_values to get the number of times each value exists in the array. You can use this to get all the values that occur only once by looking at the value in the returned array.
If you already have an array and it is in the structure described above, you should be able to just array_search(1, $array) and it will give you the key of the array with the value of 1. Or if you expect to have multiple keys with the value of 1, you can use array_keys($array, 1) and it will return an array of keys that have the value of 1. Hope this helps.

php - multidimensional array regex search and print out partial array to look at structure

I have this array structure, it is stored in a variable $xxx
Array
(
[xyz] => Array
(
[1] => 3
[0] => s
)
[d2s] => Array
(
[a] => 96
[d] => 4
)
...
)
It is a long array, and I don't want to out put the whole thing, how do print only the first 5 (1st dimension) values along with the 2nd dimension values?
Secondly, if I want this array to contain only alphabets in the FIRST dimension, how do I either delete values that don't match that requirement or retain values that match the requirement? so that my final array would be
Array
(
[xyz] => Array
(
[1] => 3
[0] => s
)
...
)
TIA
To output only the first 5 elements, use array_slice:
array_slice($arr, 0, 5)
To remove any elements whose index contains non-alpha characters.
foreach ($arr AS $index => $value) {
// Remove the element if the index contains non-alpha characters
if (preg_match('/[^A-Za-z]/', $index))
unset($arr[$index]);
}
Check it out in action.

Fetching a multidimensional array

I am trying to edit a plugin that is fetching a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data.
What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable.
The current variable
$arrayslides
returns several subarrays that look like something like this (I remove unimportant variables for the sake of briefness):
Array (
[0] => Array (
[slide_active] => 1
)
[1] => Array (
[slide_active] => 0
)
)
What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable
$arrayslides
I have tried a few array functions but have not had any luck. Any suggestions?
$arrayslides = array(0 => array ( 'slide_active' => 1, 'other_data' => "Mark" ),
1 => array ( 'slide_active' => 0, 'other_data' => "ABCDE" ),
2 => array ( 'slide_active' => 1, 'other_data' => "Baker" ),
3 => array ( 'slide_active' => 0, 'other_data' => "FGHIJ" ),
);
$matches = array_filter($arrayslides, function($item) { return $item['slide_active'] == 1; } );
var_dump($matches);
PHP >= 5.3.0
I know its not so efficient but still
foreach ($arraySlides as $key => $value)
{
if(in_array('0', array_values($value))
unset($arraySlides[$key]);
}

Remove Values from PHP Array if Present

I have the following PHP array:
Array
(
[0] => 750
[1] => 563
[2] => 605
[3] => 598
[4] => 593
)
I need to perform the following action on the array using PHP:
Search the array for a value (the value will be in a
variable; let's call it $number). If the value
is present in the array, remove it.
If someone could walk me through how to do that, it would be much appreciated.
Note: If it makes it any easier, I can form the array so the keys are the same as the values.
$array = array_unique($array) // removes dupicate values
while(false !== ($num = array_search($num, $array))){
unset($array[$num]);
}
$max = max($array);
will search for all keys with value $num and unset them
lets say your $array
$array = array_unique($array) // removes dupicate values
$array = arsort($array)
$variable = $array[0] // the maximum value in the array, and place it in a variable.
$key = array_search($array, $number);
if($key){
unset($array[$key]) // Search array for a value, value is present in array, remove it.
}
array_search() and unset() seems a good method for your sample data in your question. I'll just show a different way for comparison's sake (or in case your use case is slightly different from what you have posted here).
Methods: (Demo)
$array=[750,563,605,598,593];
// if removing just one number apply the number as an array element
$number=605;
var_export(array_diff($array,[$number]));
// if you are performing this task with more than one $number, make $numbers=array() and do the same...
$numbers=[605,563]; // order doesn't matter
var_export(array_diff($array,$numbers));
// if you need to re-index the output array, use array_values()...
$numbers=[605,563]; // order doesn't matter
var_export(array_values(array_diff($array,$numbers)));
Output:
array (
0 => 750,
1 => 563,
3 => 598,
4 => 593,
)
array (
0 => 750,
3 => 598,
4 => 593,
)
array (
0 => 750,
1 => 598,
2 => 593,
)

Categories