I have the follow code, but, i get an error in my code.
I cant find the problem but, I think it comes from:
UserManagement::findByUsername($username);
$a_allSections = UserManagement::findByUsername($username);
if($a_allSections)
{
foreach($a_allSections as $a_section)
{
echo $a_section['name'];?>
}
}
else
{
echo 'There's nothing found.' . "\n";
}
Evidently $a_allSections is not an array, so foreach complains. Use var_dump($a_allSections) to find out what exactly it is, and fix your code accordingly.
Check this way
UserManagement::findByUsername($username);
1.the function findByUsername($username) should return some values
2.the class should be included in current document.
3.Check whether your return result as array. if array means check is_array();
4.if above 3 ok in your question then you will not get the error.
$a_allSections may be empty
change condition to
if(is_array($a_allSections)){
...
}
to prevent such error on empty arrays
Related
So lets say I have this line in my php script:
array_push($arr,array($a,$b,$c));
Lets say sometimes I have a $b1 variable to put in this array
I would like to not have duplicate for the sake of maintenance how can I avoid doing this:
```
if(!isset($b1)){
array_push($arr,array($a,$b,$c,$d));
}
else{
array_push($arr,array($a,$b,$b1,$c,$d));
}
```
This is the solution I have came up with
I was hoping for some kind of syntax trick I did not know about.
I believe this works the same as Marko Mackic's solution but without using # to suppress errors, however if there was a actual need to have null values in the array this is not a solution.
function skipNull($in){
$out=array();
foreach($in as $val){
if($val!==null){
array_push($out,$val);
}
}
return $out;
}
//skip part where variable are defined
array_push($arr,skipNull(array(
$a,$b,
isset($b1)?$b1:null,
$c,$d
)));
I am confused about return statement , why we need to use return in end of function , for example
function test($a){blah;
blahh ;
blahhh;
blahhhhh;
return;}
What the use of return here? Function automatically terminates when all the statements executed , I think there is no use of return here , but this picture from http://www.w3resource.com/php/statement/return.php make me confused
So
Can someone please explain the use of return (when we not returning any value).
It depends on what you're trying to achieve.
If you write echo in several places, your code will get confusing. In general, a function that returns a value is also more versatile, since the caller can decide whether to further manipulate that value or immediately print it.
I'd recommend to stick to the convention and use return for a function.
You should check GuardClause.
Example:
function test() {
return 10;
}
$a = test(); // $a stores the value 10
echo $a; // Prints 10
echo $a + 5; // We may want to manipulate the value returned by the function. So, it prints 15.
For further reference, check What is the difference between PHP echo and PHP return in plain English?
In that context: You don't.
return breaks out of the function, but since it is the last statement in that function, you would break out of it anyway without the statement.
return passes its argument back to the caller, but since it doesn't have an argument, there is nothing to pass.
So it does nothing.
Don't assume that every piece of code you stumble across has a purpuse. It might be left over from an earlier version of the code where something else (which gave it meaning) has been removed. It might be written by someone cargo culting. It might be placeholder for future development.
"return" is important when you plan to call this function from other codes, it helps you to:
Know if the function works correctly, or not.
Obtain values from a function.
Make sure other codes are not executed after return.
It might be useless when the code is simple as your sample, let's make it more complex.
function test($a){
if(file_exists($a)){
if(is_file($a)){
return $a." IS A FILE\n";
} else if(is_dir($a)) {
return $a." IS A DIR\n";
} else {
return $a." EXISTS, BUT I DONT KNOW WHAT IT IS\n"
}
} else {
return $a." NOT EXISTS\n";
}
return 0;
}
$filecheck = test("/abc/def.txt");
if($filecheck){
echo $filecheck;
} else {
echo "unknown error";
}
Above shows how to return a value, and do some basic handling.
It is always good to implement return in your functions so you can even specify error code for your functions for reference.
Based on your example, I'll modify slightly like below:
function test($a){
blah;
blahh;
blahhh;
blahhhhh;
return 1;
}
So I know the code is running to last line.
Otherwise the function just finishes silently.
It's useful if you want a function to return a value.
i.e.
Function FavouritePie($who) {
switch($who) {
case 'John':
return 'apple';
case 'Peter':
return 'Rhubarb';
}
}
So, considering the following:
$WhatPie = FavouritePie('John');
echo $WhatPie;
would give
apple
In a really simple form, it's useful if you want a function to return something, i.e. process it and pass something back. Without a return, you'd just be performing a function with a dead end.
Some further reading:
http://php.net/manual/en/function.return.php
http://php.net/manual/en/functions.returning-values.php
To add some further context specific to the answer, if the question boils down to "Do I need to add a return for the sake of it, at the end of a function, then the answer is no. But that doesn't mean the correct answer is always to leave out your return.
it depends what you want to do with $a.
If you echo $a within the function, that function will spit out $a as soon as it is called. If you return $a, assuming you set the calling of test to a variable (i.e. $something = $test('foo')), then you can use it later on.
I'm trying to pass a value between 2 pages through a $_SESSION variable then empty it as follows:
I'm assigning the session variable with a value on one PHP page:
$_SESSION["elementName"]="a_373";
And trying to store it in a variable on another page as follows:
if (!empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
The value of $elemName is always empty when I print it out. However, I get the correct printout when I remove the $_SESSION["elementName"]=""; line from the above code.
Edit: I'm printing $elemName and not $_SESSION["elementName"] - print($elemName);
I'm on a shared hosting account with PHP 5.3.2 and register_globals set to off (as per phpinfo();).
I need to reset/empty the session variable once I get the value it has, but it's not working and this has been baffling me for the last couple of days. Any ideas why? Thanks!
EDIT:
Additional clues: I tested with the session's var_dump before the if statement and set another value for $elemName in the else section as follows:
var_dump($_SESSION["elementName"]);
$elemName="x";
if (isset($_SESSION["elementName"]) && !empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="None";
}
print("<br />".$elemName);
I got this result:
string(5) "a_373"
None
Try using isset($_SESSION["elementName"]) and unset($_SESSION["elementName"]) instead.
Check the Below code and test it
if (isset($_SESSION["elementName"]) && $_SESSION["elementName"]!="") {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
Empty only check value is empty or not, But by isset we can check varaible exit and does not content empty value
Are you printing out $elemName? If yes than there shouldn't be any blank output unless and until your else condition returns true, but if you are printing $_SESSION["elementName"] than you'll get no output as you are making it blank
$_SESSION["elementName"]="";
Correct way to remove a session var completely is to use unset($_SESSION["elementName"])
Though if you want to make it empty, == '' is enough
Also be cautious while using unset() because after you unset the session and later use that index to print, it will show you undefined index error.
Update(As #nvanesch Commented)
I guess your else condition is getting satisfied, because you are
using $elemName=""; in your else, thus you are not returned with any
output
Also if (!empty($_SESSION["elementName"])) { will return false if you are not using session_start() at the very top of your page
I once created this class in order to be able to have this ability, and it works wonderfully:
<?php
class Flash {
public function set($key, $message) {
$_SESSION["flash_$key"] = $message;
}
public function get($key) {
$message = $_SESSION["flash_$key"];
unset($_SESSION["flash_$key"]);
return $message;
}
public function has($key) {
return isset($_SESSION["flash_$key"]);
}
}
It's pretty similar to what you're trying to do, so I'm not sure why it's not working for you, but you may want to give it a try. You obviously need to have the session already started.
Sorry guys, not being lazy, I know others have had the same error message solved but I still couldn't figure it out so I had to ask.
I have 2 2d arrays each with a string and a corresponding int.
I'm trying to compare the strings in the first array to the strings in the second and if they are the same, i want to add the corresponding integers together.
I am getting the error - "Cannot use a scalar value as an array" on the 7th line
for($countOne=0; $countOne<10; $countOne++)
{
for($countTwo=0; $countTwo<10; $countTwo++)
{
if($blekko_Array['url'][$countOne]==$bing_Array['url'][$countTwo])
{
$blekko_Array['score']['$countOne'] = $blekko_Array['score']['$countOne'] + $bing_Array['score']['$countTwo'];
}
}
}
Anyone know what the problem is?
Thanks
This should do it:
foreach ($blekko_Array as &$blekko) {
foreach ($bing_Array as $bing) {
if($blekko['url']==$bing['url']) {
$blekko['score'] += $bing['score'];
}
}
}
For one thing, your code is hardwired to look through 10 items, so if your array has less than 10 entries, you'll get errors on the missing ones.
I wanted to allow only specific email domain. Actually I did it. What i wanted to ask why my first code did not work at all.
I am just trying to learn PHP so that the question may seem silly, sorry for that.
Here is my code:
function check_email_address($email) {
$checkmail = print_r (explode("#",$email));
$container = $checkmail[1];
if(strcmp($container, "gmail.com")) {
return true;
}else {
return false;
}
}
Check out the documentation for strcmp() , it will return 0 of the two strings are the same, so that's the check you want to be doing. Also, you're using print_r() when you shouldn't be, as mentioned by the other answerers.
Anyway, here's how I would have done the function - it's much simpler and uses only one line of code:
function check_email_address($email) {
return (strtolower(strstr($email, '#')) == 'gmail.com');
}
It uses the strstr() function and the strtolower() function to get the domain name and change it to lower case, and then it checks if it is gmail.com or not. It then returns the result of that comparison.
It's because you're using print_r. It doesn't do what you seem to expect from it at all. Remove it:
$checkmail = explode("#", $email);
You can find the docs about print_r here:
http://php.net/print_r
Besides that, you can just use the following (it's much shorter):
$parts = explode("#", $email);
return (strcmp($parts[1], "gmail.com") == 0);
The following row doesn't work as you think it does:
$checkmail = print_r (explode("#",$email));
This means that you're trying to assign the return value from print_r() into $checkmail, but it doesn't actually return anything (if you don't supply the second, optional parameter with the value true).
Even then, it would've gotten a string containing the array structure, and your $container would have taken the value r, as it's the second letter in Array.
Bottom line: if your row would've been without the call to print_r(), it would've been working as planned (as long as you made sure to compare the strcmp() versus 0, as it means that the strings are identical).
Edit:
Interesting enough, I just realized that this could be achieved with the use of substr() too:
<?php
//Did we find #gmail.com at the end?
if( strtolower(substr($email, -10)) == '#gmail.com' ) {
//Do something since it's an gmail.com-address
} else {
//Error handling here
}
?>
You want:
if(strcmp($container, "gmail.com")==0)
instead of
if(strcmp($container, "gmail.com"))
Oh! And no inlined print_r() of course.
Even better:
return strcmp($container, "gmail.com")==0;
No need for the print_r; explode returns a list. And in terms of style (at least, my style) no need to assign the Nth element of that list to another variable unless you intend to use it a lot elsewhere. Thus,
$c = explode('#',$mail);
if(strcmp($c[1],'gmail.com') == 0) return true;
return false;