Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I am doing wrong with the following code? I want to compare if the element $my_id is present within the array $arr. If it is present return TRUE else return FALSE.
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
else
{
return FALSE;
}
}
You could replace that with...
return in_array($my_id, $arr);
...assuming you don't really want to return FALSE if the first element does not match.
If that is actually what you wanted, you could use...
return $arr[0] == $my_id;
If you want to leave your code mostly intact, just move the return FALSE to outside of the loop body.
The issue you are having is that you aren't looping entirely through the array. You are returning true/false after the first item in the array, irrespective of subsequent array entries after [0]
Well, I believe you should remove the else statement, unless you always just have one element in the array. I mean -- from the example you're showing, you're exiting the loop with this. I doubt this is what you want.
If you just need to know, if a value is within a given array
in_array($value, $array);
Maybe you want get the index of (the first occurence of) the value too
$index = array_search($value, $array);
if ($index === false) {
// Not in array
} else {
echo $array[$index];
}
The error in Your code is to return false on $arr[$i] != $my_id. The algorithm should look something like this:
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
}
return FALSE;
P.S. This isn't the best solution for this problem in PHP language. You should use one from alex.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am looking for smart solution, maybe you could help me out. Currently I am doing an own Authentication (Separate Class) system for my Webshop project. My problem is, that I need conditional statement inside foreach loop, to return the code (see below). Any suggestions?
My code currently look like this
public function regiAuth($email, $password, $firstname, $lastname)
{
$authContainer = [$email, $password, $firstname, $lastname];
foreach ($authContainer as $a) {
return !empty($_POST[$a]);
}
}
And I want to result this (With &&)
return !empty($_POST[$email]) && !empty($_POST[$password]) &&
!empty($_POST[$firstname]) && !empty($_POST[$lastname])
I believe you could do simply by do
foreach ($authContainer as $a) {
if (empty($_POST[$a])
return false;
}
return true;
instead of checking if all of them are full, you look if there is at least one empty.
it is a good practice to stop iteration if you find one element that is not as expected, imagine if you had an array of hundreads of assertions to do.
making an full if statement would look like this, here it checks if the $_POST are not empty. && means that both have to true or false
foreach ($authContainer as $a) {
if((!$_POST[$email]) && (!$_POST[$password])){
return false;
}
}
return true;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to make a logic to check multiple conditions without using if else condition numbers of time.
I have 4 variables and i have to check whether it is empty or not.
if one of the variable is blank than want to do something.
I have function like this..
function searchResult($genre, $subject, $type, $grade){
// checking conditions here
}
please suggest me simple method.
You can use func_get_args, array_filter and func_num_args as well:
function searchResult($genre, $subject, $type, $grade){
if (count(array_filter(func_get_args())) < func_num_args()) {
echo 'One or many arguments are empty.. do something';
}
}
Pay attention to the array_filter function:
If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.
function searchResult($genre, $subject, $type, $grade){
if((!empty($genre)) && (!empty($subject)) && (!empty($type)) )
{
echo "not empty";
}
else
{
echo "empty";
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is it possible to do something like this:
if ($boolean == true) {
foreach ($variables as $variable) {
}
// some code that can be run either with a loop or without
if ($boolean == true) {
} // end the foreach loop
}
Or is there another way to do this without rewriting the same code twice just to satisfy all possibilities?
The conventional way is to always use a loop. If there is only one item, then you can still loop just once.
Contrived example
$values = …;
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $value) {
// Do your work
}
I'm not sure if I understand exactly what you're asking, but if you want to run a loop at least once, and continue looping for a condition then "Do While" is your answer. A do while works just like a while, but checks AFTER the first loop is run - meaning it always runs at least once.
PHP Docs for Do While
Do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning.
Example:
$arrayofstuff = array('one ','two ','three '); // Optional array of stuff
$i=0; // Counts the loops
echo 'starting...';
do {
// Do stuff at least once here
// Array stuff if needed
if(isset($arrayofstuff[$i])) {
echo $arrayofstuff[$i]; // Uses loop # to get from array
} else {
break; // ends loop because array is empty
}
$i++;
} while (true);
For what it's worth, forcing a variable into a single value array would probably be easier to read. As you can see there's a lot going on here for such a simple task.
(Dionne Warwick voice) That's what functions are for:
function doSomething() {
//whatever
};
if ($boolean)
for($variables as $variable) doSomething();
else
doSomething();
That kind of syntax you thought about isn't valid in PHP. It's a very clever idea though. But code maintenance of one of there would bring hell on earth. Better forget it.
why not just plain:
if($boolean){
foreach($a as $b){
// do stuff
}
}else{
// do other stuff
}
What you want would be done like so...
foreach ($variables as $variable) {
// some code that can be run either with a loop or without
if ($boolean !== true) {
break;
}
}
But this is not as readable as just using an if/else statement
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an array like this:
$age=array("Peter"=>43,"Ben"=>67); .
The array contains only two key value pairs. First i need to check if the values of these two keys are same. If same then it returns the key of these two value, otherwise return false. So here value 43 and 67 are not same so it should return false. If the two values would be same like this :
$age=array("Peter"=>43,"Ben"=>43); .
It should return the key "Peter" and key "Ben" and maybe store the keys in another array The reason is to find if two people are of same age if same age then i would like to do several other things. I will appreciate the help.
Just get the unique values and see if there is only 1:
if(count(array_unique($age)) === 1) {
return array_keys($age);
} else {
return false;
}
Because I was bored, here are two others.
Assuming only 2 elements:
if(($v = array_values($age)) && $v[0] === $v[1]) {
return array_keys($age);
} else {
return false;
}
Also, should work with multiples:
if((array_sum($age) % count($age)) === 0) {
return array_keys($age);
} else {
return false;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to define a link based of a $_GET variable, but it's saying there's an error on a line that doesn't exist...
<?php
if(isset($_GET['ref'])){
if(!empty($_GET['ref']))
{
$ref = $_GET['ref'];
}
?>
<?php
if ($ref != "") {
$link = "http://site.com/page.php?ref=$ref";
} else {
$link = "http://site.com/page.php";
}
?>
Anyone see what's up? I was pretty sure it was fine.
I've tried it multiple different ways, with isset etc... same result.
You are missing a closing }:
if(isset($_GET['ref'])){
if(!empty($_GET['ref']))
{
$ref = $_GET['ref'];
}
}
By the way, this code is quite redundant. empty() will also check whether the variable is set, so you don't need isset().
You can also use the ternary operator, which is for cases like this:
$ref = empty($_GET['ref']) ? null : $_GET['ref'];
And later check with:
if (!is_null($ref)) {
//whatever
}
Otherwise, in your code, when execution reaches if ($ref != "") {, the variable $ref might not even exist - this will throw an E_NOTICE, which you might not even see, depending on your settings.