Easiest way to check if PHP array is not empty [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I check that a PHP array is not empty?
// If $columns array is not empty...
foreach ($columns as $column) {
echo $column;
}

Why bother with functions? Empty arrays will simply return false:
if ($array) {
// array is not empty
}

Very simple: using empty() function.
if (!empty($columns)){
foreach ($columns as $column) {
echo $column;
}
}
Also can be used with other types than array.

One way is to use count()
if (count($columns) > 0) {
foreach ($columns as $column) {
echo $column;
}
}

Related

Using '&&' inside foreach? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am looking for smart solution, maybe you could help me out. Currently I am doing an own Authentication (Separate Class) system for my Webshop project. My problem is, that I need conditional statement inside foreach loop, to return the code (see below). Any suggestions?
My code currently look like this
public function regiAuth($email, $password, $firstname, $lastname)
{
$authContainer = [$email, $password, $firstname, $lastname];
foreach ($authContainer as $a) {
return !empty($_POST[$a]);
}
}
And I want to result this (With &&)
return !empty($_POST[$email]) && !empty($_POST[$password]) &&
!empty($_POST[$firstname]) && !empty($_POST[$lastname])
I believe you could do simply by do
foreach ($authContainer as $a) {
if (empty($_POST[$a])
return false;
}
return true;
instead of checking if all of them are full, you look if there is at least one empty.
it is a good practice to stop iteration if you find one element that is not as expected, imagine if you had an array of hundreads of assertions to do.
making an full if statement would look like this, here it checks if the $_POST are not empty. && means that both have to true or false
foreach ($authContainer as $a) {
if((!$_POST[$email]) && (!$_POST[$password])){
return false;
}
}
return true;

in_array() expects parameter 2 to be array, string given in orderby check function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have this function for check sortby (DESC or ASC):
function is_check_sortby($sortby,$default){
$array = array( 'DESC', 'ASC' ); //line 92
if (in_array($array,$sortby)) {
$sort = $sortby;
}
else
{
$sort = $default;
}
return $sort;
}
For check:
$sortby = is_check_sortby($_GET['order'],'DESC');
But in action i see this error:
<b>Warning</b>: in_array() expects parameter 2 to be array, string given in <b>/Applications/XAMPP/xamppfiles/htdocs/cms/class/functions.php</b> on line <b>92</b><br />
how do fix this problem ?!
Use this.
Check in_array usage in http://php.net/manual/en/function.in-array.php
function is_check_sortby($sortby,$default){
$array = array( 'DESC', 'ASC' ); //line 92
if (in_array($sortby,$array)) {
$sort = $sortby;
}
else
{
$sort = $default;
}
return $sort;
}
Reverse the order of arguments of in_array(). It should be:
if (in_array($sortby,$array)) {
}
in_array should be
in_array($sortby,$array)

refactor method with two foreach loops [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I run into refactoring problem. I have many similar methods, but i cannot find way to extract one line form them and make another private method.
private function constructRules($rules, \Languages $langs) {
foreach ($rules as $fieldType => $rule) {
foreach ($langs->all() as $lang) {
//line below changes
$langRules[$fieldType . '[' . $lang->lang . ']'] = $rule;
}
}
return $langRules;
}
I have these foreach loops in 4 different places. If i extact foreach loops and return array, I still need to make one foreach loop in method, to fill $langRules in this example. Maybe there are simple way to do it, but I am not able to see it...
Is it not just a matter of factoring out the "task" part of that code into a callback?
private function constructRulesUsingCallBack($rules, \Languages $langs, $task) {
$langRules = [];
foreach ($rules as $fieldType => $rule) {
foreach ($langs->all() as $lang) {
$task($langRules, $fieldType, $lang, $rule);
}
}
return $langRules;
}
$langRules = constructRulesUsingCallBack($rules, $langs, function (&$langRules, $fieldType, $lang, $rule) {
$langRules[$fieldType . '[' . $lang->lang . ']'] = $rule;
});
I'm not so au fait with PHP, and I am not happy with the amount of boilerplate I need in the inline function expression to work, but PHP doesn't seem to implement closure very well (that I could work out, anyhow).
However you can leave the constructRulesUsingCallBack() function as is to just handle the looping now, and simply pass a different implementation of the callback body to it each time you need to process something within those loops.
That seems to fulfil what you need it to, based on your example. If not, pls clarify and I might be able to augment this to cover your needs.

String count in $_POST [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a $_POST which contain following data
$_POST['survey_que1']
$_POST['survey_que2']
$_POST['survey_que3']
....
so on.
I have to get a count of occurrence of survey_que from $_POST.
Any Ideas please.
Restructure your data.
<input type="text" name="survey_que[]" />
This will result in $_POST['survey_que'] being an array of passed values, which you can easily use count() to get the total count.
try this
$i=0;
foreach ($_POST as $name => $val)
{
if(strpos($name,'survey_que') !== false && $name != "survey_que")
$i++;
}
echo "No of times survey_que occured in $_POST[] is ".$i;
EDIT
#shri in your code if survey_que2 is not set and survey_que3 is set then your code fails.
So try this workaround which covers all worst cases also
$i=0;
foreach ($_POST as $name => $val)
{
if(strpos($name,'survey_que') !== false && $name != "survey_que")
{
$key=explode("survey_que",$name);
if(sizeof($key) == 2 && is_numeric($key[1]) && $key[0] == "")
{
$i++;
}
}
}
echo "No of times survey_que occured in $_POST[] is ".$i;
Serialize $_POST and use "substr_count" for counting ocurrences
$how_many = substr_count(serialize($_POST), $search_string));
It's the easiest way I find but will count this text even if it's not a $_POST key value
This is working for me exactly i want.
$i = 1;
while (isset($_POST['survey_que' . $i])) {
$i++;
}
echo $i-1;
Thanks everyone for quick support.

easier way to validate $_GET id's [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
In my url i'm passing id's like this
localhost/?id=1,2,3,4,5,6,7,8,9
I was wondering if there is a better way / simpler way to validate each id without using a loop?
if (isset($_GET['id']) && !empty($_GET['id']))
{
$str = explode(',', $_GET['id']);
for($ids = 0; $ids < sizeof($str); $ids++)
{
if (!ctype_digit($str[$ids]))
{
echo 'error';
break;
}
}
}
You could just test the string with a simple regular expression, eg
if (preg_match('/^(\d+,)*\d+$/', $_GET['id']) == 0) {
throw new Exeption('error');
}

Categories