I am trying to create a function with 2 parameters one is name variable and 2 an array with name list.
If the name os in the array it should return or print 'true' in the browser otherwise it should give 'false'
For ex:
nameexistCheck('Johnny',['Jack','Sarah','Andy','Johnny']) // true
nameexistCheck('Johnny',['Jack','Sarah','Andy'])// false
I would be very grateful someone shows me how to write logic to this issue. I am a new developer and I have tried many ways but it not working.
This is one of them.
nameexistCheck($name, $names);
$names = array('Johnny', 'Jack')
foreach($names as $value){
if ($name===$value){
echo 'true';
}else{
echo 'false';
}
}
nameexistCheck('Johnny', ['Jack', 'Sarah','Johnny']);
Output is false false true
It is not working properly I need only one output true or false. And another problem is in my code I have write a name by hand to the list but, it should fill it automaticly. Please help me with this task.
It's obvious you have no idea what you're doing so I will not explain further but I will suggest you take some basic PHP tutorials. For now, this should work for you
function nameexistCheck($name, $names){
return in_array($name, $names) ? 'true' : 'false';
}
echo nameexistCheck('Johnny', ['Jack', 'Sarah','Johnny']); // true
Related
I want to thank you all in advance for taking a look at this! I am quite perplexed as to why this is not working:
My Controller:
$ownertest = $this->ion_auth->is_owner();
$grouptest = $this->ion_auth->in_group(2);
var_dump($ownertest); // echos TRUE
var_dump($grouptest); // echos TRUE
I am attempting to return "TRUE" for both $ownertest and $grouptest.
The former function result always comes back TRUE as expected, this is good.
However, the latter function result ($grouptest) only returns TRUE when I pass the number 2 directly into it.
THE PROBLEM:
I don't know why $grouptest result is returning false when I pass$groupid into it! When I echo $groupid the result is 2. Here is an example:
$groupid = $this->ion_auth->get_users_groups()->row()->id;
echo $groupid; // echos "2" in my browser
$ownertest = $this->ion_auth->is_owner();
$grouptest = $this->ion_auth->in_group($groupid)
;
var_dump($ownertest); // dumps TRUE
var_dump($grouptest); // dumps FALSE
I would have assumed that $groupid being 2 would result in a TRUE return within this function. I cannot figure this out. Does anyone have any suggestions?
I can post Ion Auth's in_group function code if needed!
Do following
Cast your variable type to integer
$grouptest = $this->ion_auth->in_group((int)$groupid);
I want to go through every property my object has and check whether it is contained in a given string. The problem is, I now have 10 properties and wrote 10 if/else-cases. I think I can compromise it by writing a foreach loop
Currently it's like this
if (strpos($localWrapper->siteContents, $project->company_name) !== false)
echo "<br>true<br>";
else
echo 'false<br>';
if (strpos($localWrapper->siteContents, $project->company_street) !== false)
echo 'true<br>';
else
echo 'false<br>';
and so on.
There must be a way that I can go through every property of the project object and check whether it is contained in the siteContents-string and then print out a true or false depended on the result.
How could I achieve this?
You can loop through it:
foreach($project as $key=>$value){
echo $key.": (".$value.") ".strpos($localWrapper->siteContents, $value) !== false ? 'true' : 'false';
echo '<br />';
}
This is really basic though, if you've read the documentation on foreach, you could figure this out yourself :)
a simple google php loop through object gives A LOT of results, all doing the same :)
If your array has arrays as values, you need to go recursive. This functions checks if the value is a string. if so test it to your searchString. If it is an array, do the same for the new array
function SeeIfMyValuesMatch($searchString, $array){
foreach($array as $key=>$value){
echo $key.' ';
// Check if the value is an array, if so, go 1 deeper
if( is_array($value){
SeeIfMyValuesMatch($searchString, $value); // on deeper
}
else{
echo strpos($searchString, $value) ? 'true' : 'false'; // or echo
}
echo '<hr />'; // This is just for looks
}
}
SeeIfMyValuesMatch($project); // And start
Small sidenote: This may result in a weird looking text, I didnt make it pretty, just to show functionallity
Could anyone please explain to me why the following line of code prints out true?
$a = "string";
if(isset($a['error'])) echo true; else echo false;
When I do a function call, I return the expected data if it worked properly, or return array("error" => $error);
Then on receiving the returned data I check if isset($var['error']) and if its not then I know I received some expected data.
I would also appreciate if you could advice me if this a good or bad way of handling data between function calls? And if there is a better "good practice" for this.
Well, this is some of PHP misbehaviors, which luckily has been fixed in some recent version.
You can address a single character in a string using the same square braces used to address an array element.
'error' evaluates to 0 and then you have got $a[0] which is set.
to fix that you have to check if $a is array first
I believe it's a bug and it's fixed in PHP 5.4+: http://codepad.viper-7.com/fz1rnT
looks like isset($str[$key]) in same way as isset($str[intval($key)]), where $str and $key are strings
To handle errors best approach are exceptions:
http://php.net/manual/en/language.exceptions.php
I'm not 100% sure why the behavior is like this, but I do know that PHP allows you to handle strings in a similar way as an array.
$a = "StackOverflow";
echo $a[2]; // a
echo $a[4]; // k
echo $a[6]; // v
echo $a[8]; // r
Now when you pass a string key as an index of the array, PHP will try to parse that string into a numerical value to use as a key.
echo $a['stack']; // S
echo $a['over']; // S
echo $a['flow']; // S
echo $a['0stack']; // S
echo $a['1over']; // t
echo $a['2flow']; // a
echo $a['3flow']; // c
echo $a['4flow']; // k
So, i have this code that seems to be doing the mechanical work correctly, avoiding to write on tables if one or more fields from a form are left empty, but the echos and messages aren't working as they supposed to:
SOLUTION TO THE PROBLEM:
I don't believe this will be useful to anyone, but just for the record, the solution is simple:
$campos = array('nome','morada','email','telemovel','codigopostal','vat');
foreach ($campos as $key => $campo) {
$campos[$key] = $_GET[$campo];
if(!isset($_GET[$campo])|| empty($_GET[$campo])){
header("Location: ../index.php?erro=".$campo);
$verifica=FALSE;
die();
}else{
$verifica=TRUE;
}
}
This will give me some problems, not what i really wanted but solves the logical problems i was having. Thanks to you all guys.
$campos = array('nome','morada','email','telemovel','codigopostal','vat');
foreach ($campos as $key => $campo) {
$campos[$key] = ($_GET[$campo]);
while(list($key, $campo)= each($campos))
if(!isset($_GET[$campo])|| $_GET[$campo]==""){
echo("não preencheu um dos campos");
$verifica = FALSE;
die();
}else{
echo $_GET[$campo]." \r\n";}
$verifica = TRUE;
}
if($verifica==TRUE){
some irrelevant code.
}
As i said, the code itself is working flawlessly, BUT if i only left 2 empty fields on the form, the echo $_GET[$campo] will be working even though the variable $verifica will be set as FALSE
AN HINT:
One of the fields is making the code to fail, is the second one, so, if i do this:
../phcexport.php?nome=myname&morada=&codigopostal=postcode&email=#.com&vat=123123&telemovel=00800
And ignore the second value from the array, the code will work like a charm, i can try as many combinations as i can as long as i left the second field empty, it will work properly, giving me the error "some field is empty", in this case i know it is, the "morada" is empty, and if i fill it in the code says "its ok, all filled in" BUT the "morada" should be the last to be filled so the code works. Funny... (I'm sorry about all the text to describe the problem, i'm Portuguese)
EDIT2: For the rest of the code i need to use $campos[$key], so attribute a key to the arrays is essencial.
The problem is that you reset $verifica in the else. So regardless if you set it once to FALSE, the last foreach iteration will determine the outcome. But you can "simplify" the whole approach to:
$verify = array_search(0, array_map("strlen", $campos)) === false;
This simply checks for the string length of each array entry. If none of them is 0, then the expression will return true for $verify;
instead of doing $_GET[$campo]=="", you can maybe use the empty function :
empty($_GET[$campo])
This should address all problems related to different data types.
Your also maybe running in a problem because you're using a variable named $campo in two different loops, try changing the variable name in the while loop to see if it works better.
Check the exact value of $campo that is causing the incorrect behaviour, then consult this table to make sure you are using the right kind of comparison
http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose
try following solution, empty fields can not pass the test
<?php
$campos = array('nome', 'morada', 'email', 'telemovel', 'codigopostal', 'vat');
$verifica = TRUE;
foreach ($campos as $campo) {
if (!isset($_GET[$campo]) || empty($_GET[$campo])) {
echo "não preencheu um dos campos" ;
$verifica = FALSE;
break;
} else {
echo $_GET[$campo] ."\r\n";
}
}
if ($verifica == TRUE) {
// some irrelevant code.
} else {
die();
}
I am in a bind, multiple times on a page for different form items, I insert a css div class into a form item ONLY if an error_array key exists, this is how I highlight a form item that has an error in it.
Works, great if I have an error because then my error array is set, problem is before an error is set, it tries to look for an array key that does not exist. I was thinking using php's isset function first would be the ticket but I guess you cannot combine isset with another function?
<?php
//this works
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)){
echo "good";
}
// this does not work, will give write errors
$search_array = array('first' => 1, 'second' => 4);
if (isset(array_key_exists('first', $search_array))){
echo "good";
}
// Here is 1 example how I need to make the end result work
$country_class = (array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';
echo '<select name="country" id="country" class="textarealong ' .$country_class. '"/>';
?>
In other parts I use it like this
<?PHP echo(array_key_exists('password', $signup_errors)) ? ' signup_error' : ' signup_good';?>
And I need to have it be a 1 line code if possible
If isset is false, the second statement wont get executed, because the parsers knows that both statements have to be true to get the whole statement true.
$country_class = ( isset($signup_errors) && array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';
BUT i would suggest you to initialize every variable you are using...
I'm not familiar enough with PHP syntax, but this sounds like a job for short-circuit evaluation, i.e. || or &&, where the second term is not evaluated if the first term alone can determine the result (if it's True in || or False in &&).
This is an old question, but it's an even simpler answer. isset checks the array and the key. This works great and doesn't generate any notices if the array is not set:
if (isset($search_array['first'])){
echo "good";
}
Or:
$country_class = isset($signup_errors['country']) ? ' signup_error' : ' signup_good';