PDA

View Full Version : array search



kishore2k9
September 2nd, 2008, 01:36 AM
hi,
how to search the string value in array.
ex: if my array contains
$ar1=array("activate"=>"1","activated"=>"3","provide"=>"1","activating"=>"2","providing"=>"3","provided"=>"2","hello"=>"6");
then how to search the string word activate exists in array or not
from the above array it has search for activate and display the result as 3 times bcz activate is there exists three rimes. how to find

hl
September 2nd, 2008, 02:05 AM
First use the [d-php]array_keys[/d-php] function to create an array of the keys as values, and then use the [d-php]array_search[/d-php] function to search through them.

darroosh
September 2nd, 2008, 04:57 AM
the function array_search may not be in the correct place here .
because ir returns only the first result it finds , and he wants to find the total , also if it finds the specified string , it returns its key not the string itself

Here U may use foreach looping to search the array for the regular expression after using array_keys as follows :


<?php

$ar1=array("activate"=>"1","activated"=>"3","provi de"=>"1","activating"=>"2","providing"=>"3","provi ded"=>"2","hello"=>"6");

$ar2=array_keys($ar1);


$number=0;

$pattern="activat.+$"; // here I defined the pattern to be any string starts with activat , notice that i remved the letter " e " to allow finding the word " activating "

foreach ($ar2 as $key)
{

if (ereg($pattern,$key))
{

$number++;
}



}

echo $number;
?>

if u understand regular expressions , u wil understand my code , and it does what u want .

When wanting to search a string in an array , I think looping is the best way , becaz it gives u much more flexibity to use regular expressions inside it , so searching inside the strings , and it gives u the right to write any code or do any thing for each element in the array , Rather than the so limited array functions that will limit u excpet when ur need matches exaclty what the function does

borrob
September 2nd, 2008, 08:35 AM
why use $ar2=array_keys($ar1);

if you can also use:



$result_arr = Array();

reset($ar1);
while ( $item = current($ar1) )
{
if ( ereg( $pattern, key($ar1) )
{
array_push( $result_arr, $item );
}
next($ar1);
}