1

Hi need help getting repeated value from give array,below is the code which im trying get max values of $values[4]

$values = array(
    "0"=> "abc",
    "1"=> "aaa",
    "2"=> "aaa|abc",
    "3" =>  "| | | | | | | | | | | | | | | | ",
    "4" => "a|b|b|c|d|e|f|g",
    "5" => "1|2|3||4|5|6"
);


foreach ($values as $key) {
$prevalues = explode('|', $key);
$count[] = count($prevalues);
}
 print_r($counts);
 $counts = array_count_values($count);
 arsort($counts);
 echo $max= key($counts);


Array
 (
    [0] => 1
    [1] => 1
    [2] => 2
    [3] => 17
    [4] => 8
    [5] => 8
)
print_r($max );

Currently, I am getting $max = 1; I need $max to be 8.

4 Answers 4

1

Why not:

foreach ($values as $key=>$value)
    $max = max(substr_count($value,'|')+1,$max);

echo $max;

No array splitting or storing arrays. :)

Sign up to request clarification or add additional context in comments.

4 Comments

@user1477117 Is that a question?
@iambrainsreed : i need get the most repeated values in an array too,how can i get the repeated values using your method
what are the "most" repeated values? every value that is repeated inside one string? or just the top3?
@Mohammer count($values) which are repeated, in above array 8 repeated
1

If you already have you array $counts with the values and you need only to find the max value in the array like i think you are asking, then there is a built in function for this already in php.

$max = max($counts);

$max will be equal to 17.

Documentation: http://php.net/manual/en/function.max.php

In regards to finding the must repeated value in the array as per your comment to iambrainsreed:

You could use array_count_values().

$valueCount = array_count_values($counts);
print_r($valueCount);

Would output:

Array
(
    [1] => 2
    [2] => 1
    [17] => 1
    [8] => 2 
)

From there you can use that data for what you need.
Documentation: http://php.net/manual/en/function.array-count-values.php

1 Comment

better yet, iambriansreed's idea to incorporate substr_count(), you can get the documentation on that at. php.net/manual/en/function.substr-count.php
0

You can use max() to find the highest value in an array, here's an example

echo max(array(1, 5, 7, 2, 3));

This should give you 17

foreach ($values as $item)
{
    $temp[] = substr_count($item, "|") + 1;
}

echo max($temp);

1 Comment

but i`m not able get max values from above code which im using
0

You could probably use substr_count($key,'|')+1 instead of explode.

EDIT: I am thinking that I don't really understand the question clearly, perhaps could you write more clearly? Why are you using the key function?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.