View Full Version : Searching an array - function

07-20-2012, 02:52 AM
Hi, I want to create a function which takes a form input as its only parameter. I want the function to search an array of characters and if that character is found within the user input, then the function returns true, if no characters are found within the user input I want the function to return false.

Here is what I have made:

function check_string($data){
$chars = array('!','?','~','@','"','','$','%','^','&','*','(',')','[',']','#','/','<','>','+','=','-','_','.',',',':',';','{','}','|');

if(strstr($data, $chars[$i])){
$result = TRUE;
return $result;


$result = FALSE;
return $result;


$result = check_string($_POST['user']);
echo $result;

If I enter any characters in the array into the form field, it echo's "1", and if I do not enter any of those characters, it gives errors. It doesn't reload, it just stays loading forever and crashes.

Does anyone know what I am doing wrong?

07-20-2012, 01:01 PM
It probably gets stuck in an infinite look because $chars is not a number but an array, you need to use the array size as your terminator.

$count_chars = count( $chars );

for( $i=1; $i<$count_chars; $i++ ){

07-20-2012, 01:13 PM
Ah thank you very much.

Can I also ask, you know in JavaScript when doing a for loop, you do:

for(var i=0;i<=someArray.length-1;i++){
//code here....

Why won't PHP allow you to use the length property?

Kind regards,


07-20-2012, 01:20 PM
Also could I just ask, when creating an action file, should I check the form fields with isset() BEFORE or AFTER sending the form field value to the check_string() function?