简体   繁体   中英

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

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
 )  

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.

还有array_map()函数,该函数将给定函数应用于数组的每个元素。

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM