Even if array for foreach is empty, run it - php

I've came across a little problem. Well I'm getting from wordpress database some user_meta data, which is stored as array, by declaring variable $all_meta_for_user = get_user_meta($user_id, 'meta_key', false). Then, I'd like to check if some specific data is present, and if so, do something, if not, do something else. I've got somewhere here at stackoverflow a hint, that I can achieve it in that way:
foreach($all_meta_for_user as $key=>$val) :
if (array_key_exists ('some_key', $val) && array_key_exists ('some_other', $val)) { do something } else {do something else }
endforeach;
And that works good, as long as associated 'meta_key' is present in database (which is obvious :)). But what, if it's not? Then, again obviously, foreach is false and it doesn't run.
Basically, I'd like to show content after else even if the array is empty. How I can alter my code, to achieve that? I think I could get it working, if I first check if array is empty, if no - do code with foreach, if yes - do my else. But the problem is, in my else there's a lot of code, so I'd like to avoid duplicating it.
So, simply, the question is, how to make that in a nice way, that will not double my code :)
Thanks!
PS I really couldn't find appropriate topic name. If someone have a better idea how to name it, please leave a comment so I can change it! Thanks!

You can create your "else" function, and combine that with the if/else idea. That way you won't have any repetition, just function calls:
function elseFunction() {
//do something else
}
if (!empty($all_meta_for_user)) {
foreach($all_meta_for_user as $key=>$val){
if (array_key_exists ('some_key', $val) && array_key_exists ('some_other',$val)){
// do something
}
else {
elseFunction(); // this is changed
}
}
}
else {
elseFunction();
}

Related

Using isset to display page content

I am having an issue using isset to display content on a page.
My PHP file is called messages.php
I am directing my users with links to this URL: messages.php?inbox using if(isset($_GET['inbox']))
{ } to display the users inbox. Same principle with the other users options such as compose message is: messages.php?compose again using isset
The only problem I have is that I cannot stop people from manually typing stuff like domain.com/messages.php or domain.com/messages.php?somethingrandom.
Is there a way to direct users to messages.php?inbox when they type in the address bar something that isnt assigned to isset?
I did try to use switch but couldnt seem to get it to work properly with how ive laid out my HTML.
An example of the whole file is here http://pastebin.com/SfqN2L7g
I am fairly new to PHP and think I may have gone down the complicated route.
Any advice would be appreciated.
Thanks
The answer you added already would work, but I usually like having an array of valid options which I could maybe check against later on.
$validPages = array('inbox', 'compose');
$pageFound = false;
foreach ($validPages as $validPage) {
if (isset($_GET[$validPage])) {
$pageFound = true;
break;
}
}
if (! $pageFound) {
header('Location: /messages.php?inbox');
}
Thanks to the help of Marcos PĂ©rez Gude, the answer is as follows:
if(isset($_GET['inbox']) || isset($_GET['compose'])){
//Then do below
}else{
header("Location: messages.php?inbox");
exit;
}

Efficient way to check multiple variables declarations?

In a project of mine I am working with a sequence of pages that each give information that is used in the next, with POST and session variables. Simple example:
Page 1: enter name -> page 2 display name; ask birth date -> page 3 display name and birth date.
If a user goes directly to page 3 I want to display a message that s/he has not entered a name and/or birth date and should try again. Currently I am still doing it like so. On page 2:
if (isset($_POST['name'])) $_SESSION['name'] = $_POST['name'];
and page 3:
if (isset($_SESSION['name'])) $name = $_SESSION['name'];
if (isset($_POST['bday'])) $_SESSION['bday'] = $_POST['bday'];
as declarations and in the body an if-clause like
if (isset($name) && isset($_SESSION['bday'])) {
// do main stuff
else {
// display error message
}
The example is simple enough, but in the real world my code has a lot more variables and data from the forms, and putting all this first in variable assignments and then in an if-clause is tiring and seems not efficient to me. Is there a better, more straightforward way to check things like this? Or is what I posted the best, most-used way to go?
You can use one call to isset to check several variables.
isset($_SESSION['name'], $_SESSION['bday'], ...)
Or you can write your own function like
if (variablesFilled(['name', 'bday', ...])) { }
function variablesFilled($array) {
foreach ($array as $entry) {
if (!isset($_SESSION[$entry])) {
return false;
}
}
return true;
}
I believe you just need to write some helper methods. One to rewrite $_POST data to $_SESSION, dumb as this:
function copyPostToSession(array $fields) {
foreach($fields as $field) {
if(isset($_POST[$field])) {
$_SESSION[$field] = $_POST[$field];
}
}
}
so instead of if forest, you do:
copyPostToSession(array('name','bday'));
(additionally you can count how many fields were present and return true or false if there's mismatch) and the other (pretty similar) to check if you got all the required data in $_SESSION.
PHP's isset() function is a variadric function.
You can put as many arguments as you want:
isset($a, $b, $c)
...which translates to:
isset($a) && isset($b) && isset($c)
Hope it helped!
Seperate functions tend to differ a bit on a per server case. You could try calculating the time to perform a function a large number of times and compare which is faster.
But, yeah, that looks like fairly fast code there.
Might be worth trying a switch case statement as an alternative perhaps?

PHP - Use a URL Key to get data from a separate file not normally index

I'm not a PHP dev and I have little experience with it. I ask for your forgiveness and assistance.
Here's my problem:
I have a script and I need to be able to append a 'key' (I don't know what else to call it) like:
http://my-web-address.com/packages.php?key=secret
When this key is present, I need to run the code responsible for extracting the data from a .json file in a separate directory. (Normally, the code wouldn't index this directory. It should only indexes it when the key is present in the URL.)
I believe this code to be the foreach section in the link above.
I'm having a hard time explaining this in a way that makes sense, so I guess it's easier to show you what I mean.
I know it should be easy; at first I thought I could simply do it with something like this:
if ($key == "secret") {
$document['packages'][] = getPackageData("secretdirectory/secret.json");
}
But alas, simply appending that didn't make it work.
Any ideas?
As Ron Dadon said, but with a slight modification:
sanitize($value) {
// Sanitize the key - see below
return $value;
}
$key = sanitize($_GET['key']);
if ($key == "secret") {
$document['packages'][] = getPackageData("secretdirectory/secret.json");
}
However you should sanitize that input, as anyone can change the key. Here are some resources on that:
Clean & Safe string in PHP
Remove all special characters from a string
The ultimate clean/secure function
You need to use the GET array:
if ($_GET['key'] == "secret") {
$document['packages'][] = getPackageData("secretdirectory/secret.json");
}

Better way of doing isset($variable) and check variable value

I was wondering if there's a better way than what I always do to check the value of a variable that might not be set? For example :
if(isset($_SESSION['super_user']) && $_SESSION['super_user'] == true) {
echo 'hi super user';
}
It would much simpler to just do this :
if($_SESSION['super_user']) {
echo 'hi super user';
}
But I would end up with a notice of undefined index. Is there another way of doing such kind of simple validation or I must stick with my actual way of doing it?
Thanks
if (!empty($_SESSION['super_user'])) {
// ...
}
You could initially set $_SESSION['super_user'] to false and only set it to true if the user is a super user. Then you can always use if ($_SESSION['super_user']) {}.
For the particular example your current code could be shortened to
if(!empty($_SESSION['super_user']))
however, the right way would be
if ($_SESSION['role'] == 'super_user')
I was wondering if there's a better way than what I always do to check the value of a variable that might not be set?
Yes. Always define all your variables. Like one I posted above. Always have a role element for all your users and there will be no need to check if it ever exists.

How do I use a while loop with counter for echoing else statement?

I'm not a full time PHP programmer by any means, but wondering what the most efficient way to do this would be? I am running a fetch to grab some data that I want to display on a page. The query results usually have multiple rows.
The following below works great, except for the last else statement for showing none. This part doesn't work. Basically I want to display my rows of data and if nothing exists, throw out a message saying "none."
I did some reading around and it looks like with a while loop + multiple result sets you can't simply just use the standard else... both with !empty or isset.
Someone mentioned doing a counter? Would this be the best way to accomplish this. Open to any suggestions as I will probably be adding more data like this in the future and would like to do it in the correct fashion.
Thanks!
while($myvariable = oci_fetch_assoc($stmt))
{
if(!empty($myvariable))
{
echo "<tr><th>DISPLAY FIELD NAME:</th><td>" . $myvariable['myrowdata'] . </td></tr>";
}
else
{
echo "<tr><th>DISPLAY FIELD NAME:</th><td>None</td></tr>";
}
}
Look at oci_fetch_assoc on php manual. This function is typically called in a loop until it returns FALSE, indicating no more rows exist. So you dont need any other if or else inside your while loop.
Do the check before the loop by fetching the first row and checking if it's not FALSE; then, if it's not, feed it to the loop and fetch the next row at the END of the loop. This is called "priming the loop" and isn't uncommon.
if(!($myvariable = oci_fetch_assoc($stmt))) {
echo "<tr><th>DISPLAY FIELD NAME:</th><td>None</td></tr>";
} else {
while($myvariable) {
echo "<tr><th>DISPLAY FIELD NAME:</th><td>" . $myvariable['myrowdata'] . </td></tr>";
$myvariable = oci_fetch_assoc($stmt));
}
}
I think this reference would help you about using function oci_fetch_assoc:
http://php.net/manual/en/function.oci-fetch-assoc.php#100304
Your while statement will run only if you get something in your "$myvariable", therefore your if statement is redundant and your else is irrelevant in this case. If you want to run something along the lines of what you're thinking, you can do "oci_fetch_all()" and then loop through and do your if/else.

Categories