-3

Actually I have made small programme in php using simple array and search name from array and my programe given below :

$n = array("Akki","Amesh","Akit","Baa","aaakk");

$hint = "";

$find = "ak";

if ($find !== "") {

    $find = strtolower($find);

    $lwn = strlen($find);

    foreach($n as $gt){     
        if(stristr($find, substr($gt,0,$lwn))){
            if($hint === ''){                   
                $hint .= $gt;
            }else{          
                $hint .= ",$gt";
            }
            }
    }
}
echo ($hint == "") ? "NNN" : $hint ;

My query how to check $hint got data are single & double and how to add comma after got name from array

Like I have searched name using word ak and i got two name Akki and Akit. and its perfect but i want to know how to add comma between that name.

And What does check this condition : ($hint === '')

tell me if anyone know my query.

Akki
  • 1
  • 3

4 Answers4

1

Just to help out with an easier solution:

$hint = implode(", ", preg_grep("/^$find/i", $n));
  • Grep your array for the following and return matches:
    • Look at the start of the string ^ for $find case-insensitive i
  • Join on a comma ,
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

To add comma change your else condition :

else{          
                $hint .= ","."$gt";
            }
Minar Mnr
  • 1,376
  • 1
  • 16
  • 23
0

your if condition: if($hint === ''){ will check for $hint's value and datatype as well. if datatype matches then it will check for the value.

so in your case it will check for string datatype and then compare with $hint's value i.e. blank string.

Also as mentioned in answer you should use implode function.

Jigar Shah
  • 6,143
  • 2
  • 28
  • 41
  • you can read more about difference b/w `===` and `==` here: https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp – Jigar Shah Jun 28 '17 at 17:34
0

What this code does:

        if($hint === ''){                   
            $hint .= $gt;
        }else{          
            $hint .= ",$gt";
        }

is see if $hint is empty (which it will be the first time the preceding if condition is true, since it is initialized to empty at the beginning). This is used to add a comma only if there is already a value in $hint. The === operator simply compares value and type as opposed to only value comparison when using ==. It is really not necessary here.

Does that answer your question?

EDIT: Regarding the comma, as far as I can see the comma is added currently. The code has potential for improvement, but works.

Michael Heumann
  • 100
  • 1
  • 2
  • 11