I need to be able to test if $post_count is equal to any number in a given array. Here is an example of what I am trying to achieve:
$posts_even = array(2,4,6,8,10);
$posts_odd = array(1,3,5,7,9);
$posts_ev3 = array(1,4,7,10);
$posts_ev4 = array(1,5,9);
--
$post_count=1;
$post_count=++; //in wordpress loop so each subsequent post is +1
--
if ($post_count= //any value in $posts_ev4) :
echo 'this'
else :
NULL;
endif;
I have been able to make this work using the or operator but I end up with very long blocks of code.....
if (($post_count=1) || ($post_count=2)) :
echo 'this'
else :
NULL;
endif;
I am guessing there is a simpler way to do this but I am new to PHP so I am not sure! Any help would be greatly appreciated.
Try:
if (in_array($post_count, $post_ev4)) {}
See: in_array()
Use in_array() to check if value exists in array.
if (in_array($post_count, $posts_ev4)) :
echo 'this'
else :
NULL;
endif;
Check out the isset() function in the PHP Manual.
There are array functions in php. Ypu can use "is_array" function to check whether its array or not. & to check for a value you can use "in_array" function.
if(is_array($array) && in_array($post_count,$array))
{
// do operation
}
Related
I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.
you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>
if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.
Use empty:
if (empty($myArray)) {
...
}
Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>
It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}
<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}
It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.
I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>
I am looking for an optimized way to do something like this:
Check if what am I receiving from a function:
Is set
Is an array
If so, I would like to directly assign it to a variable.
For that propose, I would do something like:
Let's suppose that I'm calling a function that returns me an array (or not).
<?php
$data_table = isset(Api::get($url)) && is_array(Api::get($url)) ? (array)Api::get($url) : array();
?>
However, doing something like this would require three calls to the function:
The first, to check in an if statement if it is really returning something
The second to check if the return is an array
The thing to assign the return to $data_table variable
I've thought about doing the following, but I'm not sure how it could work like this:
<?php
$data_table = isset($result = Api::get($url)) && is_array($result) ? (array)$result : array();
?>
Please let me know your thoughts.
Thanks.
You can use empty(). From the manual:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
It doesn't quite check for whether it's an array, rather whether the variable (of many types) is empty, but it's a shorter way than what you're doing. I think if you want to check for an array and for isset, that's what you'll have to do - no way around it.
<?php
$data_table = !empty($result) ? $result : array();
?>
I have a URL which i pass parameters into
example/success.php?id=link1
I use php to grab it
$slide = ($_GET["id"]);
then an if statement to display content based on parameter
<?php if($slide == 'link1') { ?>
//content
} ?>
Just need to know in PHP how to say, if the url param exists grab it and do the if function, if it doesn't exist do nothing.
Thanks Guys
Use isset()
$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
EDIT:
This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.
$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
if(isset($_GET['id']))
{
// Do something
}
You want something like that
Here is the PHP code to check if 'id' parameter exists in the URL or not:
if(isset($_GET['id']))
{
$slide = $_GET['id'] // Getting parameter value inside PHP variable
}
I hope it will help you.
It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:
Change your first line to
$slide = '';
if (isset($_GET["id"]))
{
$slide = $_GET["id"];
}
I know this is an old question, but since php7.0 you can use the null coalescing operator (another resource).
It similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value.
$slide = $_GET["id"] ?? 'fallback';
So if $_GET["id"] is set, it returns the value. If not, it returns the fallback. I found this very helpful for $_POST, $_GET, or any passed parameters, etc
$slide = $_GET["id"] ?? '';
if (trim($slide) == 'link1') ...
Why not just simplify it to if($_GET['id']). It will return true or false depending on status of the parameter's existence.
Why is this not possible?
if(!empty( _MY_CONST)){
...
But yet this is:
$my_const = _MY_CONST;
if(!empty($my_const)){
...
define( 'QUOTA_MSG' , '' ); // There is currently no message to show
$message = QUOTA_MSG;
if(!empty($message)){
echo $message;
}
I just wanted to make it a little cleaner by just referencing the constant itself.
See the manual: empty() is a language construct, not a function.
empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
So you'll have to use a variable - empty() is really what you want in the first place? It would return true when the constant's value is "0" for example.
Maybe you need to test for the existence of the constant using defined() instead?
Just letting you know that you can do
if(!empty(MY_CONST))
since PHP 5.5.
You can get along with this if for some reason you are still not using PHP 5.5.
if (defined('MY_CONST') && MY_CONST) {
echo 'OK';
}
if (!empty(constant('MY_CONST')) {
...
}
mixed constant ( string $name )
Return the value of the constant indicated by $name, or NULL if the constant is not defined
http://php.net/manual/en/function.constant.php
what about strlen?
if(strlen(MY_CONST) == 0)
If constant defined and need check is empty or not, for example you use it in config file, you can use !MY_CONST:
define('MY_CONST', '');
if (!MY_CONST) {
echo 'MY_CONST is empty';
}