Why this function always returning false? - php

I have a very basic question. It's may very poor question but I just want to clear my confusion.
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value)
{
return true;
}
return false;
}
//return false;
}
Why this function always returning false.
for example If I have $numbers = array(1,2,3). If I match 2 with this array it should return me true else return me false. But why it's returning always false ?

why it's returning always false ?
Try to "execute" this function yourself acting as a computer.
If the first element of array is equal to $user_value, it will return true. If not - it will move futher down the loop and return false.
Probably, you wanted to check all the elements of array for equality. In this case you need to use this:
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value)
{
return true;
}
}
return false;
}

The return false is in the wrong place, it should be where you commented it out but not in the other place it is.
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value)
{
return true;
}
}
return false;
}
If the return is in the other place, it will return false after failing to find your value in the first array cell.

You dont need to create a function for it when php has already have it in_array
you can use it like in a single line
$result = in_array($user_value,$array)
It will return true if the value is found and false if not found.
You need not to loop through the array

You have the return false inside of the loop. That means if the first element isn't a match, it will return false. It won't even check the second element of your array

Your function will be returning false, unless it matches the first value in the array.
This is because at the moment your logic is in the wrong order, and if the first value in the array doesn't match $user_value the function returns false.
You could solve this problem by moving the return false; line of code below the loop.
Now the loop will run through all the values in the array. It will return true if it matches one, and if it has checked all the values and there is no match then it will then return false.
function check_array($user_value,$array)
{
foreach ($array as $key => $value) {
if($value==$user_value) return true;
}
return false;
}
This should clear up the logic mistake in your code. However I up-voted Veerendra's in_array() answer as that means there is no need for any loop, cutting down your code.

Related

PHP - how to use a 'break;' in a ternary operator

I have the following function. It compares one value to each value in an array.
function catExists($id) {
$cats = getCats();
foreach ($cats as $cat) {
if ($cat['id'] == $id) {
return true;break;
} else {
return false;
}
}
}
I'm trying to shorten the whole thing by using ternary operators.
function catExists($id) {
foreach (getCats() as $cat) return ($cat['id'] == $id) ? true : false;
}
The problem I have is that I can't use break; when the condition turns to true. i.e The returned value will keep reverting back to false unless the true condition is at the end of the array.
Is their a way that this can be achieved on a single line?
Thanks
That's not what ternary operators are meant to do. Keep it simple (KISS). You don't need the break statement at all since return ends the function execution and returns the program control back to the main program.
I'd write it this way:
function catExists($id) {
foreach (getCats() as $cat) {
if ($cat['id'] == $id)
return true;
}
return false; // 'return true' never happened, so return false
}
If you really want to make it one line, you could use array_column() in conjunction with array_search() like so:
function catExists($id) {
return array_search($id, array_column(getCats(), 'id')) !== FALSE;
}

Looping through validation checks, and return false if one of the checks returns false?

Im trying to figure out a way to loop through objects with a validation method that returns true or false, and then in the end know if any of the object returned false.
$validate_form = true;
//Loop through groups
foreach ($this->field_groups as $field_group) {
//Loop through fields
foreach ($field_group->fields as $field) {
$validated = $field->validate($data[$field->name]);
//if any of these returned false, set $validate_form to false
}
}
return $validate_form;
But i simply can't rap my head around how to achieve this. I have thought about using an array, and then check if any of the values in the array has 'false' in it. But that seems a bit clumsy.
I feel like there must be a "best practice" on how to do this?
UPDATE: Its important that each field runs the ->validate() method. even fields that comes after the first "false".
Thanks!
You could go with this :
$validate_form = true;
//Loop through groups
foreach ($this->field_groups as $field_group) {
//Loop through fields
foreach ($field_group->fields as $field) {
$validated = $field->validate($data[$field->name]);
//if any of these returned false, set $validate_form to false
if (!$validated)
{
$validate_form = false;
break;
}
}
}
return $val_form;
The "break;" is going to stop the loop.

php foreach iteration over object property array not incrementing the value

Please help! I have been staring at this for too long. I have a property of an object that is an array of objects. I want to pass in an object to a method of the parent object and search through that array property for a match, and if one is found return the index. Otherwise, I need it to return -1. For some reason, it is not iterating. If I echo out what should be the $order->product property (where the index is pointing during the loop), it is unchanging. I have dumped the array and I know it contains different values. I can show you a big var dump, but I figured I would first ask if there is a simple error or something else that is obvious to you that I have missed.
public function getItemIndex($prod) {
if (isset($this->orders)){
foreach($this->orders as $key => $order) {
if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
return $key;
} else { return -1; }
}
}
else {
return -1;
}
}
If anyone has any ideas, I am open to discuss and post more information as needed. Thank you for your time.
You are ALWAYS returning a value on the first iteration, either the $key or -1. Try removing the else statement that you currently have. This will allow you to fully iterate over the entire array.
public function getItemIndex($prod) {
if (isset($this->orders)){
foreach($this->orders as $key => $order) {
if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
return $key;
}
}
}
return -1;
}
This will ONLY return -1 once it has iterated over everything and found nothing to match. It will still return $key if it finds a match.

Return true if and only if all values in array are true?

So I have an array that contains all of the function calls to check the input of a form. I then have a foreach loop through the array to see if the returns from the validate functions are true or false. Depending on that outcome the function that the foreach is in returns either true or false. The problem I'm trying to figure out is how to return true just once if all of the validate functions come back true.
Here is my code:
public function valInputs()
{
$valArray = array(
valName($firstName),
valName($lastName),
valPhone($phone),
valEmail($email)
); // these functions return true/false depending on validation
foreach($valArray as $value)
{
if(!$value)
{
return false;
break;
}
else
{
return true; // the problem is, true gets returned X number of times
}
}
}
Any ideas on how to keep true from returning multiple times? Thank you for any help.
The return call stops the foreach loop AND the function. You can in fact just return true beneath the loop:
foreach($valArray as $value)
{
if(!$value)
{
return false;
// break is not needed, and should NOT be used in this case,
// as it stops the foreach loop.
// It will never be reached anyways, seeing how you return false just above.
}
}
return true;
If it reaches the end of the loop, it means it hasn't returned false. Hence it should return true.
An interesting way to do it would be
public function valInputs()
{
$valArray = array(
valName($firstName),
valName($lastName),
valPhone($phone),
valEmail($email)
); // these functions return true/false depending on validation
return array_product( $valArray ) === 1;
}
Why not just:
public function valInputs() {
return (valName($firstName) && valName($lastName) && valPhone($phone) && valEmail($email));
}
This will return true if all of them are true, false if at least one of them is false. Frankly I'm not sure why would you need a foreach loop there.
By definition, return ends the function. You can't return more than once.
Look at pst's comment, check to see if you are calling that function multiple times.

user input - testing array for empty values *

check::empty_user()
below will test an array for 'empty' values -
NULL, FALSE, 0, or ' '
/*check*/
class check
{
static function empty_user($a)
{
return (int)!in_array('',$a);
}
}
function test_empty(array $array) {
foreach($array as $elem) {
if (!empty($elem)) return false;
}
return true; // no element, or no non-empty element
}
in_array('', $array);
I think that is what you're after?
Your function isn't going to test anything other than the first element of your array. Return causes the function to cease execution.
PHP has empty and isset functions, either of those should be suitable testing array elements. To test the entire array you can use in_array and look for empty values. However you'll have to implement your own method for processing nested arrays.
You test empty could also be the folowing:
// if the array has at least one empty value
function test_empty(array $array) {
foreach($array as $elem) {
if (empty($elem)) return true;
}
return false;
}
In summary use
empty() or in_array()
and make note that:
$value=='' tests for null, false, 0, and ''

Categories