Is there a better/shorter way to perform the following:
$stock_array = array("soccer" => "0");
if (count($stock_array) == 1 && in_array('0', $stock_array)) {...}
I want to check if the array has 1 element, and the value is 0.
Thanks in advance
Based on your title, this provides if the count is one and its value is 0
$count = array_count_values($stock_array);
if ($count == array('0' => 1)) {
//something
}
Or you can also use array_filter() with empty(), if you are looking for a pre-function kind of answer: This will return True if all the values in the array are empty or 0.
if (empty(array_filter($stock_array))) {
//something
}
Yes, you can try using the following code.
if (array_search('0', array_values($stock_array)) == 0) {...}
But this doesn't tell if the array has only this element.
From your question, I can understand you are trying to do:
Check the length of array to be 1.
Check if the value exists in the array.
The solution I provided, checks if that's the first value of the array. But to check the length of array, you need to have another as well.
Related
In laravel I have send the ajax response to the controller. there I have check the condition to check the count of the response geo as if(count($request['geo'])) and for some reason I want to check the condition if no count for geo as if(count($request['geo']) == 0).but its not working.
How to check the condition 'if no count for geo' in laravel
if $request['geo'] contains an array, then count($request['geo']) == 0 will be true for empty array [].
But if $request['geo'] contains a string (e.g. '[]') - it won't work and you can't use count() for strings. For checking empty strings you can use $request['geo'] == '' or !$request['geo']
Probably you need to check the type of value first, e.g. using is_array($request['geo'])
P.S. !$request['geo'] works for both - empty arrays and empty strings
You can check like this
if(empty($request['geo'])){
// your code
}
You can use php function gettype and count.
So you can use following code:
if(gettype($request['geo']) == 'array') {
if (count($request['geo']) == 0) {
// your code here
} else { // count > 0
// your other code here
}
}
Hope to helpful.
I have a VERY simple code, I dont know what I am doing wrong. I am sending post variables with Ajax, there are 3 checkboxes (an array) name="options[]".. I am receiving the right array, if I check Option1, Option2 or Option3, I get the correct Array.. but when I try to check and confirm them with isset() or with array_key_exist() it does not give me the right answers.. For example, if I only check Option 1 and 3, I get the following in the POST
[options] => Array
(
[0] => option_one
[1] => option_two
)
I need to do some action only IF the certain key does NOT exist in the array.. I tried something like below..
if (array_key_exists("option_one", $_POST['options'])) {
echo "Option one exists";
} else {
echo "option one does not exist";
}
it returns flase results, then I tried using ! (not) before it, that returns the same result. Then I tried with isset($_POST['options']['option_one']) without any luck.. then I tried the following function to check again within the array..
function is_set( $varname, $parent=null ) {
if ( !is_array( $parent ) && !is_object($parent) ) {
$parent = $GLOBALS;
}
return array_key_exists( $varname, $parent );
}
and used it like this
if (is_set("option_one", $_POST['options'])) {
echo "Option one exists";
} else {
echo "option one does not exist";
}
nothing works, it simply returns false value. I tried with $_REQUEST instead if $_POST but no luck, I have read many threads that isset() or array_key_exists() returns false values.. What is the solution for this ? any help would be highly appreciated.. I am tired of it now..
regards
option_one is not a key in the array, it's a value. The key is 0. If anything, use:
in_array('option_one', $_POST['options'])
array_key_exists looks for the keys of the arrays. You are looking for the value. :)
What you want is
/**
* Check wheter parameter exists in $_POST['options'] and is not empty
*
* #param $needle
* #return boolean
*/
function in_options($needle)
{
if (empty($_POST['options']))
return false;
return in_array($needle, $_POST['options']);
}
Are you sure you are getting the correct information in your options[] array? If you clicked option 1 and option 3, shouldn't the array look something like this?
[options] => Array
(
[0] => option_one
[1] => option_three
)
Since isset() is a language construct and not a function, you may be able to rework the validation to be more efficient.
function in_options($needle)
{
//Checking that it is set and not NULL is enough here.
if (! isset($_POST['options'][0]))
return false;
return in_array($needle, $_POST['options']);
}
The function empty() works, but I think that $_POST['options'][0] only needs to be checked for isset() at this point.
Learning PHP and I have a question.
How does one obtain an element from an array and determine if it is equal to a static value? I have a return set from a query statement (confirmed the array has all values).
I tried:
<? if($row["rowValue"] == 1) {
}
?>
I was expecting the value to be 1, but it's returning null (as if I'm doing it wrong).
You're pretty much there; something like this should confirm it for you:
echo "<p>Q: Does ".$row["rowValue"]." = 1?</p>";
if($row["rowValue"] == 1) {
echo "<p>A: Yes ".$row["rowValue"]." does equal 1</p>";
} else {
echo "<p>A: No, '".$row["rowValue"]."' does not equal 1</p>";
}
If that's still returning 'No' you could try viewing the whole of the $row array by doing a var dump of the array like so:
var_dump($row);
This will give you detailed output of how the array is built and you should be able to see if you are calling the correct element within the array.
What is returning null?
Try this:
if($row["rowValue"] === 1) { ... }
Make sure there is an element in $row called rowValue.
maybe try:
<? if($row[0]["theNameOfAColumn"] == 1) {
}
?>
Usually databases return rows like row[0], row[1], row[2], etc.
I am not sure what exactly you are doing, but try using array_filp() which will Exchanges all keys with their associated values
than you can do like
if($row["rowValue"] == 1) {
http://in1.php.net/manual/en/function.array-flip.php
If you're pulling it from mysqli_fetch_row then it wants a number, not a column name. If it's being pulled from mysqli_fetch_array then it will accept a column name.
http://php.net/manual/en/mysqli-result.fetch-row.php
http://php.net/manual/en/mysqli-result.fetch-array.php
I need to check array value, but when array is empty, I get this: Error: Cannot use string offset as an array
if (!empty($items[$i]['tickets']['ticket'][0]['price']['eur'])) { //do something }
How to do it correctly?
You need to check if the variable is set, then if it is an array and then check if the array's element is set. The statements of the if will be executed in order and will break when one is false.
if(isset($items) && is_array($items) && isset($items[$i]['tickets']['ticket'][0]['price']['eur'])) {
//jep it's there
}
Or just try it (extra sipmle variant):
if (!isset($items[$i]['tickets']['ticket'][0]['price']['eur'])) {
// do action
}
We gave a given array which can be in 4 states.
array has values that are:
only arrays
only non-arrays
both array and non array
array has no values
Considering than an array-key can only be a numerical or string value (and not an array), I suppose you want to know about array-values ?
If so, you'll have to loop over your array, testing, for each element, if it's an array or not, keeping track of what's been found -- see the is_array function, about that.
Then, when you've tested all elements, you'll have to test if you found arrays, and/or non-array.
Something like this, I suppose, might do the trick :
$has_array = false;
$has_non_array = false;
foreach ($your_array as $element) {
if (is_array($element)) {
$has_array = true;
} else {
$has_non_array = true;
}
}
if ($has_array && $has_non_array) {
// both
} else {
if ($has_array) {
// only arrays
} else {
// only non-array
}
}
(Not tested, but the idea should be there)
This portion of code should work for the three first points you asked for.
To test for "array has no value", The fastest way is to use the empty() language construct before the loop -- and only do the loop if the array is not empty, to avoid any error.
You could also count the number of elements in the array, using the count() function, and test if it's equal to 0, BTW.
Some precalculation:
function isArray($reducedValue, $currentValue) {
// boolean value is converted to 0 or 1
return $reducedValue + is_array($currentValue);
}
$number_of_arrays = array_reduce($array, 'isArray', 0);
Then the different states can be evaluated as follows:
only arrays
count($array) == $number_of_arrays
only non-arrays
$number_of_arrays == 0
both array and non array keys
count($array) != $number_of_arrays
array has no keys
empty($array);
So you just need to write a function that returns the appropriate state.
Reference: in_array, array_reduce, empty