Return statement in PHP functions [duplicate] - php

This question already has answers here:
Return always return false
(3 answers)
Closed 9 years ago.
I'm having some problems with a Return statement in PHP. The thing is that, no matter what happend inside my function I always get a false value out of the function. I really think that is because of the Return statement because I try to use it in other functions and I don't get a diferent value.
public function valid_token ()
{
if (!isset($_SESSION['token']) || $this->token != $_SESSION['token'])
{
$this->errors[] = "Formulario incorrecto";
}
return count($this->errors)? 0 : 1;
}
Out of this function I always get a false value (0). The same happends when i call:
public function valid_data ()
{
if (empty($this->sectorName) || empty($this->sectorInfo) || empty($this->sectorCat))
{
$this->errors [] = "Datos incorrectos";
}
return count($this->errors)? 0 : 1;
}
Of course, I call both functions when I have already sent the form and have set the token.

Because you are just counting not checking,Try this
return count($this->errors) > 0 ? 0 : 1;

More simply,
return !$this->errors;

Related

function returns true false or maybe [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a function that returns true or false based on its algorithm and works fine.
function abc(){
if(somecondition){
return true;
}else{
return false;
}
}
and later on in my code I do
if(abc()){
//code if the function returns true
}else{
//code if the function returns false
}
and this works flawlessy.
Now I want to handle a situation where the function should return a "maybe" status so that later on I perform an additional check. So my pseudo code becomes:
function abc(){
if(somecondition){
return true;
}elseif(someothercondition){
return 'maybe';
}else{
return false;
}
and later on in my code I do
if(abc()){
//code if the function returns true
}elseif(abc()=='maybe'){
//code if the function returns maybe
}else{
//code if the function returns false
}
Is this going to work? Is this the correct way to handle this?. I am asking since the maybe condition is a very remote situation in my code that is hard to replicate and this makes it hard for me to test directly
It's a cleaner approach to return nullable bool, than mixed.
So your implementation would be
function abc(): ?bool
{
if (somecondition) {
return true;
} elseif (someothercondition) {
return null;
} else {
return false;
}
}
Where the null value stands for "maybe".
You'll also need to use strict comparison (===). In loose comparison (==) null would equal to false.
$abc = abc();
if ($abc === false) {
// no
} elseif ($abc === null) {
// maybe
}
The condition after return evaluates to either true or false, so there's no need for the if/else.
function abc(){
/*if(somecondition){
return true;
}else{
return false;
}*/
return somecondition;
}
or
function abc(){
/*if(somecondition){
return true;
}elseif(someothercondition){
return 'maybe';
}else{
return false;
}*/
return someothercondition ? 'maybe' : somecondition;
}
the condition the more specific should be the first to evaluate abc()=='maybe'.
so change this
if(abc()){
//code if the function returns true
}elseif(abc()=='maybe'){
//code if the function returns maybe
}else{
//code if the function returns false
}
to that to be more specific
if(abc()==='maybe'){
//code if the function returns maybe
}elseif(abc()){
//code if the function returns true
}else{
//code if the function returns false
}
The accepted answer is the correct answer to my question but the solution I finally implemented is taking input from a comment by #nicohaase. I splitted in two the function so that the code becomes:
function abc(){
if(somecondition){
return true;
}else{
return false;
}
}
function def(){
if(someothercondition){
return true;
}else{
return false;
}
}
then I do:
if(abc()){
//do something
}else{
//this is false, check other conditions
if(def()){
//do something else
}else{
//execute code if all return false
}
}
I have moved the "maybe" outside the function so the functions return a boolean as expected and the code is cleaner to read.

Recursive Function returns null value [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
Below recursive function i am trying to get array of codes. For example input 'bme4', output should be like [0]=>'bme'[1]=>'bm'[2]=>'b'. But the return value is null eventhough i can get the correct return value with var_dump().
function get_parent_cat_code($code, $category_codes) {
$parent_cat_code = substr($code, 0, -1);
if ($parent_cat_code != ''){
$category_codes[] = $parent_cat_code;
get_parent_cat_code($parent_cat_code, $category_codes);
} else {
var_dump($category_codes);
return $category_codes;
}
}
Solved!
function get_parent_cat_code($code,$category_codes){
$parent_cat_code=substr($code, 0, -1);
if($parent_cat_code!=''){
$category_codes[]=$parent_cat_code;
return get_parent_cat_code($parent_cat_code,$category_codes); //i used return for calling recursive function.
}else{
var_dump($category_codes);
return $category_codes;
}
}

Class to check empty inputs validation with php OOP [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 3 years ago.
I dont understand why this is not working and any advice for oop im beginner on oop paradigm
My class
class formvalidation {
public function check_empty_input($inputs=[]){
$checked = false;
foreach($inputs as $valor){
if(empty($valor)){
$checked = false;
break;
} else {
$checked = true;
}
}
if($checked = true){return true;}
else {return false;}
}
}
Check if posts are empty
$formvalidation= new formvalidation();
$inputs = array($_POST['name'],$_POST['email'],$_POST['pass'],$_POST['confirmpass']);
if($formvalidation->check_empty_input($inputs))
Well, the problem is in the return if, you are using = as comparison operator, where instead you should have used ==, and so the function will return always true... also you should use a static function from the moment that you don't need a object to invoke this function, try with this one:
<?php
class formvalidation {
public static function check_empty_input($inputs = []) : bool {
$everything_filled = true; //start with this supposition
foreach ($inputs as $valor) {
if (empty($valor)) {
$everything_filled = false; // is something is empty, than the supposition is false
break;
}
}
return $everything_filled; // return the supposition result value
}
}
$is_my_inputs_filled = formvalidation::check_empty_inputs([
$_POST['name'],
$_POST['email'],
$_POST['pass'],
$_POST['confirmpass'],
]);
If it doesn't work, please explain better what you mean with "doesn't work"

return an array from a recursive function [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I think I need some explanations about the recursivity... I looked at some same issues over forums but it didn't help me a lot.
Here is my function :
public function tas ($nb_gift, array $winners)
{
if ( !empty( $nb_gift ) ){
$id_winner = rand( 10, 15 );
if ( !$this->_in_array_r($id_winner, $winners) ){
$existing_user = $this->getWinner( $id_winner );
}
if( !empty( $existing_user ) && $nb_gift > 0 ){
$winners[] = array( $existing_user, 'iphone5');
$this->tas($nb_gift - 1, $winners);
}
else {
if($nb_gift > 0)
{
$this->tas($nb_gift, $winners);
}
}
}
else {
//print_r($winners);
return $winners;
}
}
At the end I have an array composed of the winners. Even if the print_r works, the return doesn't give me back my array.
Does the function need some optimisation ?
You are never returning anything from the first if branch. If you call tas() initially and it goes into the first if branch, it never returns, hence the caller is never getting anything back.
Recursion is nothing special, really. You call a function, you get a result:
$winners = tas();
Simple. Internally that functions may call other functions:
function tas() {
return foo();
}
There's no restriction that tas can't call itself, but it's still bound by the same rules of returned data:
function tas() {
if (...) {
foo(); // <-- doesn't return anything
} else {
return foo();
}
}
Just substitute foo() in the above example by tas() for the same concept, but including recursion.

PHP return syntax [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the PHP ? : operator called and what does it do?
Can someone please tell me what this 'return' php code means / does:
return ($status=='SUCCESS' && $blocked=='YES') ? $reason : false;
I'm familiar with the regular return $variable type of statements in php, but I don't get what the specific brackets ( ) and ? question marks and the ": false" does.
(this is the return statement at the end of a php function)
It's a ternary statement. It's basically a shorthand notation for if/else.
In your example it would read like: If $status is equal to "success" and $blocked is equal to "Yes" return $reason, else, return false;
That's a ternary, or conditional operator, it's the same as if you had:
if($status=='SUCCESS' && $blocked=='YES'){
return $reason;}
else{
return false;
}
It means the same as this:
if($status == 'SUCCESS' && $blocked == 'YES')
{
return $reason;
}
else
{
return false;
}

Categories