How to generate a longer isset() statement in PHP? - php

I have an interesting question today. Lets say I have an array of form fields:
array('field1', 'field2', 'field3');
I would basically want to generate an if statement which check if all of the provided fields are exists or not.
So something like this:
function ($array){
$stm = '';
foreach($array as $key){
$stm .= 'isset($_POST['.$key.']) && ';
}
if (rtrim($stm, ' && ')){
echo 'Fields are exists.';
}
}
The problem with the above function is that it takes the created statement as a String and not a variable, so it always exsits. Is there any way that I can generate something like this, which would work?

You're thinking about this the wrong way. If I understood correctly, you have an array of values, that are also POST keys, and you want to check if all of them are set. In this case I'd do something like:
function isset_multiple($array){
foreach($array as $post_key){
if(!isset($_POST[$post_key])) // if one of them is not set, return false
return false;
}
return true; // none of the foreach loops returned false, so all must be set
}

What you can do is check if array keys are set by using variable names, for example
$keyName = "field1";
if ( isset($_POST[$keyName]) === true ) { /* ... */ }
The example above can be implemented in a foreach loop.

Just execute the isset and count:
function ($array){
$count = 0;
foreach($array as $key){
if (isset($_POST[$key]) $count++;
else // you can already exit here...
}
if (count($array) === $count){
echo 'All fields exist.';
}
}

Try this..
function arrayHasKeys(array $array, array $keys)
{
return !((bool) array_diff_key($array, $keys));
}
var_dump(arrayHasKeys($_POST, array('field1', 'field2', 'field3')));
Its quite simple and reusable. Its not a good practice to use global vars inside a function.

Related

How can we use a condition inside a foreach loop

The following foreach query is inserting only values in ['options']['Colors'] and not those in ['options']['Color'] ???
Updated Question:
if (!is_array($value['options']['Colors'])) {
$value['options']['Colors'] = array($value['options']['Colors']);
}
if (!is_array($value['options']['Color'])) {
$value['options']['Color'] = array($value['options']['Color']);
}
if(isset($value['options']['Colors'])) {
$colorArr = $value['options']['Colors'];
} else if(isset($value['options']['Color'])) {
$colorArr = $value['options']['Color'];
}
foreach ($colorArr as $colors) {
$stmt->execute(array(':pid' => $PID, ':colors' => $colors));
}
You can't do this as this way... it does not make a sense. what exactly do you want to do ?
if you want check the existence of a value in array you could use in_array function like this:
if(in_array("someValue", $someArray)) {
// Do something ...
}
We can not use OR in foreach loop. Instead we can use if statement to verify and then can go ahead like below:
if(isset($value['media']['options']['Colors'])) {
$colorArr = $value['media']['options']['Colors'];
} else if(isset($value['media']['options']['colors'])) {
$colorArr = $value['media']['options']['colors'];
}
foreach ($colorArr as $colors) {
// You can use $colors now where you want
}
If you really insist on having the array such that either key may be used, I suggest you convert all to lower case before using them
foreach($value['media']['options'] as &$key => $value){
if($key == 'Colors'){
$key = 'colors';
}
}
Then try using the array as before, but without the need for the OR statement checking for 'Colors'
you could merge the arrays then loop, be careful of key conflicts though. can one option have both a "color" and a "Color" in which case it can get messy really fast, which one do you use, the first, the second, both, none?
$colors = array_merge ($value['media']['options']['Colors'], $value['media']['options']['colors'] );
foreach($colors as $color ){
}

Shortcut to isset() and assigning values

Is there a shortcut method to assigning $_GET['values'] to variables?
I currently do like others do:
if(isset($_GET['type'],$_GET['case'])
$type = $_GET['type'];
$case = $_GET['case'];
Is there a cleaner method to do this instead of doing like below separately.
$type = $_GET['type'];
$case = $_GET['case'];
http://docs.php.net/extract
I think you're looking for extract function.
extract($_GET); //now, all of the functions are in current symbol table
Well, with array map you can you get the case not just once, but all at once, and you can also check for isset() and empty() at the same time too.
Suppose, you have this URL: read.php?id=1&name=foo&job=student&country=Brazil
Your problem is fetching the $_GET type, and you may need to check if is it empty/isset or not right?
Well, first you create a function to iterate through it.
function checkGet($val){
return (isset($val) && !empty($val)) ? $val : null;
}
Then, you callback that function with array_map()
$check = array_map('checkGet', $_GET);
And that is it!
If you were to do var_dump($check); now, you would get get all the types, and values:
array (size=4)
'id' => string '1' (length=1)
'name' => string 'foo' (length=3)
'job' => string 'student' (length=7)
'country' => string 'Brazil' (length=6)
Meaning, after this, instad of doing:
if(isset($_GET['something']) && !empty($_GET['something']))
$var = $_GET['something'];
echo $var;
Just do:
echo $check['something']
The only one-line code I can think of, to make sure that you still do the necessary checks, is
$type = (isset($_GET['type'])) ? $_GET['type'] : 'a default value or false';
Reading comments, I understand you may want to do this:
foreach($_GET as $key=>$value) {
$$key = $value;
}
I would suggest though, to always initialize the variables you need only. The above code will result in getting unknown variables, which may actually give the user a way to manipulate your script.
Example:
index.php?ExpectedVar=1&UserDefinedVar=2
will generate the following variables in your code:
$ExpectedVar // 1 <- you wanted this one
$UserDefinedVar // 2 <- but what about this?
What if you had this script called by some other script?
Then even if you have this code at the top of your file, you may have some variables overwritten from a user defined $_GET!
Disaster case Scenario:
script1.php
<?php
$tableToDelete = "old_products";
include("script2.php");
?>
script2.php
<?php
foreach($_GET as $key=>$value) {
$$key = $value;
}
// user added &tableToDelete=users
// DROP TABLE $table
// will gloriously delete users
?>
Instead by writing a few lines with the original code I posted, you can get the variables you need at the start of your php script and use them with a clear mind.
Try like
foreach($_GET as $key=>$value) {
$get_arr[$key] = $_GET[$key];
}
print_r($get_arr);
I would do it that way, this way you make sure that it will only return TRUE or FALSE
if (!isset($_GET['type']) || empty($_GET['type'])) {
// Display error
} else {
$type = $_GET['type'];
$case = $_GET['case'];
}
Or you can do it that way as well
$type = (isset($_GET['type'])===false)?'':trim($_GET['type']);
$case = (isset($_GET['case'])===false)?'':trim($_GET['case']);
$_GET is table, so you can easy use foreach function
For example
foreach ($_GET as $key => $value) {
... = $value;
}
If you would like to create variables with $key names use variable variables
PHP Manual Variable Variables
You can do it through extract()
extract($_GET, EXTR_PREFIX_ALL, 'g');
so that
$_GET['val'] becomes $g_val
Note the third parameter: g it prepends g_ to the keys.
This (untested) class should help you:
class MyGet {
public static $myValues = array();
public static function setMyValues($keywords, $where) {
MyGet::$myValues = array();
for ($index = 0; $index < count($keywords); $index++) {
if ((!(isset($where[$keywords[$index]]))) || (empty($where[$keywords[$index]]))) {
MyGet::$myValues = array();
return false;
}
MyGet::$myValues[$keywords[$index]] = $where[$keywords[$index]];
}
}
}
You can use it like this:
if (MyGet::setMyValues(array(0 => "type", 1 => "case"), $_GET)) {
//the values are initialized
} else {
//the values are not initialized
}

If true use foreach loop, else use while

I'm trying to link the MySQL while loop into foreach loop using something like this :
if($something == true){
foreach($array as $arr){
} else {
while($row = mysql_fetch_array($mysql_query)){
}
// loop instructions
}
It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database
I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :
if($something == true){
$mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
$mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}
while($row = mysql_fetch_array($mysql_query)){
...
That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop
P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above
Put your processing into a function:
function process_data($data) {
// do stuff
}
if($something){
foreach($array as $arr){
process_data($arr);
}
} else {
while($row = mysql_fetch_array($mysql_query)){
process_data($row);
}
}
The other answers here are fine, but you'd be better served just to make sure that $array is a valid array regardless of something ... How about
if (!something){
$array = array();
while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}
foreach($array as $arr){
// do work
}
You'd probably get a better answer if you expanded the scope of what you've explained a bit. Without knowing what the something is and what the data is, plus the ultimate objective then it's hard to tell what kind of structure you should be using.
It seems to me that you could achieve this by just using a function, if the code inside the loop is the same. Like this:
if($something == true)
{
foreach($array as $arr)
{
doWork($arr);
}
}
else
{
while($row = mysql_fetch_array($mysql_query))
{
doWork($row);
}
}
function doWork($arr)
{
//...
}
You cannot nest loop instructions inside a loop like this. You'll need to have two separate loops completely inside the IF statements.
if($something == true){
foreach($array as $arr){
// do work
}
} else {
while($row = mysql_fetch_array($mysql_query)){
// do work
}
}
Maybe you could look at from this viewpoint. And take note that this code uses mysql_fetch_assoc() instead of mysql_fetch_array(). Try both functions and look at the resulting rows with var_dump(). You will see that mysql_fetch_array() has twice as much data. You may want that, but probably not.
if ($something !== true)
{
$array = array();
while($row = mysql_fetch_assoc($mysql_query_result_resource))
{
$array[] = $row;
}
}
foreach($array as $arr)
{
/* PROCESS */
}

iterate through array, number of keys is variable, the first value being processed differently

Hi I have a PHP array with a variable number of keys (keys are 0,1,2,3,4.. etc)
I want to process the first value differently, and then the rest of the values the same.
What's the best way to do this?
$first = array_shift($array);
// do something with $first
foreach ($array as $key => $value) {
// do something with $key and $value
}
I would do this:
$firstDone = FALSE;
foreach ($array as $value) {
if (!$firstDone) {
// Process first value here
$firstDone = TRUE;
} else {
// Process other values here
}
}
...but whether that is the best way is debatable. I would use foreach over any other method, because then it does not matter what the keys are.
Here is one way:
$first = true;
foreach($array as $key => $value) {
if ($first) {
// something different
$first = false;
}
else {
// regular logic
}
}
$i = 0;
foreach($ur_array as $key => $val) {
if($i == 0) {
//first index
}
else {
//do something else
}
$i++;
}
I would do it like this if you're sure the array contains at least one entry:
processFirst($myArray[0]);
for ($i=1; $i<count($myArray); $1++)
{
processRest($myArray[$i]);
}
Otherwise you'll need to test this before processing the first element
I've made you a function!
function arrayCallback(&$array) {
$callbacks = func_get_args(); // get all arguments
array_shift($callbacks); // remove first element, we only want the callbacks
$callbackindex = 0;
foreach($array as $value) {
// call callback
$callbacks[$callbackindex]($value);
// make sure it keeps using last callback in case the array is bigger than the amount of callbacks
if(count($callbacks) > $callbackindex + 1) {
$callbackindex++;
}
}
}
If you call this function, it accepts an array and infinite callback arguments. When the array is bigger than the amount of supplied functions, it stays at the last function.
You can simply call it like this:
arrayCallback($array, function($value) {
print 'callback one: ' . $value;
}, function($value) {
print 'callback two: ' . $value;
});
EDIT
If you wish to avoid using a function like this, feel free to pick any of the other correct answers. It's just what you prefer really. If you're repeatedly are planning to loop through one or multiple arrays with different callbacks I suggest to use a function to re-use code. (I'm an optimisation freak)

php if array key exists inside multidimentional array

how can i check if logo exists in this array called $attachements print_r is below:
Array (
[logo] => /home/richar2/public_html/ioagh/images/stories/jreviews/20100510115659_1_img.gif
)
when theres no logo, the array print_r's
Array ( )
i tried:
if (isset($attachments['logo']) ) {..}
but the conditional code runs when there is no logo
Use the function array_key_exists.
http://php.net/manual/en/function.array-key-exists.php
It's very stange that isset() is not working, I am pretty sure it should. Maybe you have a problem elsewhere in your code.
Anyway, if you want to try something else, there is a specific function: array_key_exists()
This works for me as expected:
$arr['logo'] = '/home/richar2/public_html/ioagh/images/stories/jreviews/20100510115659_1_img.gif';
print_r($arr);
if (isset($arr['logo'])){
echo $arr['logo'];
}else{
echo 'Key doesn\'t exist!';
}
Are you sure you set $arr['logo'] = null, not $arr['logo'] = ''?
For the latter you can also check
if (isset($arr['logo'] && !empty($arr['logo'])){
...
}
but the conditional code runs when
there is no logo
You could construct an else clause to take appropriate action:
if (isset($attachments['logo']))
{
// logo is set
}
else
{
// loto is not set
}
Or simply try this:
if (array_key_exists('logo', $attachments))
{
// logo is set
}
More info on array_key_exists
You can use array_key_exists.
you could write it like:
function md_array_key_exists ($key, $array)
{
foreach ($array as $item => $val)
{
if ($item === $key)
{
return true;
}
if (is_array ($val))
{
if (true == marray_key_exists ($key, $val))
return true;
}
}
return false;
}

Categories