PHP array element comparison - php

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

Related

check the variable have no count

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.

Count array & in_array in one function

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.

match a variable with at least one value in an array - php

I have one variable that comes from a database.
I then want to check whether that value is the same of one of the values in an array.
If the variable matches one of the array values, then I want to print nothing, and if the variable does not match one of the array values, then I want to print something.
This is the code I have been trying without luck, I know that contains is not valid code, but that is the bit I cannot find any info for:
<?php
$site = getStuff();
$codes = array('value2', 'value4');
if ($codes contains $site)
{
echo "";
}
else
{
echo "something";
?>
So if the database would return value1 for $site, then the code should print "something" because value1 is not in the array.
The function you are looking for is in_array.
if(in_array($site, array('value2', 'value4')))
if(!in_array($site,$codes)) {
echo "something";
}
To provide another use way to do what the other answers suggest you can use a ternary if
echo in_array($site, $codes)?"":"something";

Php test empty string

I have a bit of php code that I'm not understanding why it is acting as it is. I have a variable called contactId that I want to test to see if it is empty. However even if it is empty it evaluates to true. Code is below. Thanks in advance.
print "*".$contactId."*<br/>";
if($contactId != '')
{
//queryContact($contactId);
print "Contact Present<br/>";
}
result returned to screen is:
**
Contact Present
If you want to see exactly what your string is, simply use var_dump(), like this, for instance:
var_dump($contactId)
instead of
print "*".$contactId."*<br/>";
Couple of things you can try:
if (!empty($contactId)) {
// I have a contact Id
}
// Or
if (strlen($contactId) > 0) {
// I have a contact id
}
In my experience I have often used the latter of the two solutions because there have been instances where I would expect a variable to have the value of 0, which is valid in some contexts. For example, if I have a drink search site and want to indicate if an ingredient is non-alcoholic I would assign it a value of 0 (i.e. IngredientId = 7, Alcoholic = 0).
Do it with if (isset($contactId)) {}.
You likely want:
if (strlen($contactId))
You'll want to learn the difference between '' and null, and between == and ===. See here: http://php.net/manual/en/language.operators.comparison.php
and here: http://us3.php.net/manual/en/language.types.null.php
In future, use if(!empty($str)) { echo "string is not empty"}.

PHP: testing for existence of a cell in a multidimensional array

I have an array with numerous dimensions, and I want to test for the existence of a cell.
The below cascaded approach, will be for sure a safe way to do it:
if (array_key_exists($arr, 'dim1Key'))
if (array_key_exists($arr['dim1Key'], 'dim2Key'))
if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))
echo "cell exists";
But is there a simpler way?
I'll go into more details about this:
Can I perform this check in one single statement?
Do I have to use array_key_exist or can I use something like isset? When do I use each and why?
isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like
isset($arr[1][2][3])
is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).
However, if you have
$arr['a'] = null;
then
isset($arr['a']); // false
array_key_exists('a', $arr); // true
comment followup:
Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:
isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.
I was having the same problem, except i needed it for some Drupal stuff. I also needed to check if objects contained items as well as arrays. Here's the code I made, its a recursive search that looks to see if objects contain the value as well as arrays. Thought someone might find it useful.
function recursiveIsset($variable, $checkArray, $i=0) {
$new_var = null;
if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable[$checkArray[$i]];
else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable->$checkArray[$i];
if(!isset($new_var))
return false;
else if(count($checkArray) > $i + 1)
return recursiveIsset($new_var, $checkArray, $i+1);
else
return $new_var;
}
Use: For instance
recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))
In my case in drupal this ment for me that the following variable existed
$variables['content']['body']['#object']->body['und']
due note that just because '#object' is called object does not mean that it is. My recursive search also would return true if this location existed
$variables->content->body['#object']->body['und']
For a fast one liner you can use has method from this array library:
Arr::has('dim1Key.dim2Key.dim3Key')
Big benefit is that you can use dot notation to specify array keys which makes things simpler and more elegant.
Also, this method will work as expected for null value because it internally uses array_key_exists.
If you want to check $arr['dim1Key']['dim2Key']['dim3Key'], to be safe you need to check if all arrays exist before dim3Key. Then you can use array_key_exists.
So yes, there is a simpler way using one single if statement like the following:
if (isset($arr['dim1Key']['dim2Key']) &&
array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...
I prefer creating a helper function like the following:
function my_isset_multi( $arr,$keys ){
foreach( $keys as $key ){
if( !isset( $arr[$key] ) ){
return false;
}
$arr = $arr[$key];
}
return $arr;
}
Then in my code, I first check the array using the function above, and if it doesn't return false, it will return the array itself.
Imagine you have this kind of array:
$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );
You can write something like this:
$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );
if( $arr ){
//You can use the variable $arr without problems
}
The function my_isset_multi will check for every level of the array, and if a key is not set, it will return false.

Categories