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;
}
Related
I am trying to loop through an array assigned to an object. The function entity_products_check() must compare the submitted product to an array of pre-held values from a database.
The foreach loop must evaluate to true in the provided test example. However, for reasons I cannot understand the === operator returns empty (i.e. null) and XAMPP evaluates it to false. For some bizarre reason this occurs only if one checks for the first value. For any other result it executes correctly.
I do not understand why this happens?
$entity=array("products"=>array("machine", "lollipop"));
class Borrowing_Cost
{
public array $entity;
public array $item;
public array $borrowing;
public function __construct($entity, $item, $borrowing)
{
$this->entity = $entity;
$this->item = $item;
$this->borrowing = $borrowing;
}
public function entity_products_check($arg){
$is_item = "";
**foreach ($this->entity["products"] as $value){
if($value === $arg){
$is_item = "true";
} else {
$is_item = "false";
}
}**
return $is_item;
}
}
$borr = new Borrowing_Cost($entity, $item, $borrowing);
echo $borr->entity_products_check("machine") . "<br>";
In your code you compare every item against the value you are looking for, so after it finds it, it will still go onto the next item and set the flag to false.
This code sets to false at the start and only ever flags it true when found and then stops...
public function entity_products_check($arg){
$is_item = "false";
foreach ($this->entity["products"] as $value){
if($value === $arg){
$is_item = "true";
break;
}
}
return $is_item;
}
Or you could use in_array() to check if the value is in the array for you...
public function entity_products_check($arg){
return in_array($arg, $this->entity["products"])
? "true" : "false";
}
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.
How can I use foreach to return true or false.
For example, this isn't working.
function checkArray($myArray) {
foreach( $myArray as $key=>$value ) {
if(!$value == $condition) {
return false;
}
else {
return true;
}
}
if ($checkArray == true) {
// do something
}
What is the correct syntax for using foreach as true/false function? If you can't do it, could you use it to change an existing variable to true/false instead?
You would return true if the element was found/condition is true. And after the loop return false - if it had been found, this statement wouldn't have been reached.
function checkArray($myArray) {
foreach($myArray as $key => $value) {
if ($value == $condition) {
return true;
}
}
return false;
}
if (checkArray($array) === true) {
// ...
}
Of course true and false are interchangeable, depending on what output you expect.
If you're just trying to find a value you can use
if (in_array($lookup, $arrayToSearch)) { }
It'll be more efficient than enumerating the whole array.
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.
Can we break execution of callback once condition satisfied with one element of array?
ex .
$a = array(1,2,3,4,5);
foreach($a as $val){
if ($val == 3){
break;
}
}
if we write call back for it, it will be as below
$result = array_filter($a, function(){
if ($val == 3){
return true;
}
});
In callback it will go through all array element, in spite of condition is being satisfied at 3. rest two elements 4, 5 will also go through callback
I want such function in callback, which will break callback one desired condition match and stop execution of rest of elements
Is is possible?
You can do that with a static variable. A static variable is of local scope inside the callback function but preserves its value between calls.
It behaves like a global variable in terms of its value, but with a local scope:
$callback = function($val)
{
static $filter = false;
if ($val == 3) {
$filter = true;
}
return $filter;
};
This callback will return false until $val == 3. It then will return true.
I dont think you can achieve this with array_filter, but you can do something like this:
$a = array(1,2,3,4,5);
try {
array_walk($a, function($value, $key) use(&$a) {
if ($value == 3){
throw new Exception("condition match");
}
unset($a[$key]);
});
}
catch(Exception $e) { }
var_dump($a);