0

I a string that is coming from my database table say $needle. If te needle is not in my array, then I want to add it to my array.

If it IS in my array then so long as it is in only twice, then I still want to add it to my array (so three times will be the maximum)

In order to check to see is if $needle is in my $haystack array, do I need to loop through the array with strpos() or is there a quicker method ?

There are many needles in the table so I start by looping through the select result.

This is the schematic of what I am trying to do...

$haystack = array();

  while( $row = mysql_fetch_assoc($result)) {
   $needle = $row['data'];

    $num = no. of times $needle is in $haystack //   $haystack is an array

    if ($num < 3 ) {
        $$haystack[] = $needle; // hopfully this adds the needle
        }

     } // end while. Get next needle. 

Does anyone know how do I do this bit:

$num = no. of times $needle is in $haystack

thanks

4 Answers 4

1

You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance:

$original_values_count = array_count_values($values);

foreach ($values as $value)
    if ($original_values_count[$value] < 3)
        $values[] = $value;

As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually.

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

Comments

1

Did you mean array_count_values() to return the occurrences of all the unique values?

<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?> 

The output of the code above will be:

Array ( 
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
 )  

Comments

0

There is also array_map() function, which applies given function to every element of array.

Comments

0

Maybe something like the following? Just changing Miek's code a little.

$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
    $haystack[] = $needle;

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.