开发者

PHP: How do I check the contents of an array for my string?

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


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.


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
 )  


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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜