CudoX
CudoX

Reputation: 1003

php function return a Boolean and use it on condition

im not sure on how i am going to explain this correctly.

I wanted a function to validate a string which i figured correctly.

But i want the function to return a boolean value.

And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.

i am not sure if this is correct.

<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
    if(!empty($myString)) {
        if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
            }
    }
    else {
        return false;
    }
}

if(validatestring == FALSE) {
    //put some codes here
}
else {
    //put some codes here
}
?>

EDIT : Now what if there are more than 1 condition inside the function?

<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
    if(!empty($myString)) {
        if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
            return true;
        }
        else {
            retun false;
        }
    }
    else {
        return false;
    }
}

if(validatestring($myString, $myString2) === FALSE) {
    //put some codes here
}
else {
    //put some codes here
}
?>

Upvotes: 0

Views: 5884

Answers (4)

vitthal
vitthal

Reputation: 11

store $string1 to $myString in the function myString=string1

<?php
$string1 = 'hi';
function validatestring($myString) {
        myString=string1;
    if(!empty($myString)) {
        return true;
    }
    else {
        return false;
    }
}

if(validatestring() === FALSE) {
    //put some codes here
}
else {
    //put some codes here
}
?>

Upvotes: -1

Damien Pirsy
Damien Pirsy

Reputation: 25435

Sidenote, since empty() already returns false ,you could simplify by doing:

function validateString($string){
  return !empty($string);
}

if(validateString($myString){
  // ok
}
else {
 // not ok
}

To make a check and test later:

 $check = validateString($myString);

 if($check){ }

There's no need to check == false or === false, the function already returns a boolean, it would be redundant.

Upvotes: 1

Realit&#228;tsverlust
Realit&#228;tsverlust

Reputation: 3953

Functions need brackets and parameter. You dont have any of them.

This would be correct:

if(validatestring($myString) === false) {
    //put some codes here
}

An easier and more elegant method would be this:

if(!validatestring($myString)) {
    //put some codes here
}

Upvotes: 2

dayuloli
dayuloli

Reputation: 17001

<?php
$string1 = 'hi';
function validatestring($myString) {
    if(!empty($myString)) {
        return true;
    }
    else {
        return false;
    }
}

if(validatestring($string1) === FALSE) {
    //put some codes here
}
else {
    //put some codes here
}
?>

Upvotes: 1

Related Questions