Codeigniter array value check - php

I have an array like these
$data=array(
'a'=>'value1',
'b'=>'value2',
'c'=>'value3',
'd'=>array('e'=>'value4','f'=>'value5' ),
);
By using CI how to get the value of 'e' and how to check 'e' is equal to any value or not.

This isn't related to CodeIgniter.
You can just do this: $data['d']['e']
And then to check if it's equal to any value do this:
if ($data['d']['e'] == $anyValue) {
// do something
}

You can get the value as in the case of a two dimensional array..$data['d'] will select the array inside.Then get the value of 'e' or 'f' as $data['d']['e'] or $data['d']['f']. If you want to compare try:
if ($data['d']['e'] == $Value) {
//put your code here.....
}

You can use
echo "<pre>";
print_r($data['d']['e']);
die();
inside your code to check what value you have inside the index 'e'. Always use this technique. Very handy.
By the way, this is standard/raw PHP technique, not CI. You can use raw PHP in CI, there's nothing wrong with that.
Checking whether the value you have inside index 'e' is equal to a specific value, is a very basic thing you probably might've learned back in high school or grad school. It's by using an if() statement that you can compare your 'e' value with the specific value you have.
if($data['d']['e'] == 'somevalue')
{
//do your work here
}

Related

Check if running script is in array

I'm trying to run a function but only on specific pages. I thought this would be fine...
$allowed_pages = array('/admin/update.php', '/admin/system.php', '/admin/install.php');
if($_SERVER['SCRIPT_NAME'] == $allowed_pages) {
myCoolFuntion();
}
...but it doesn't seem to work as expected and the myCoolFuntion() runs regardless of what page I am on.
If I echo $_SERVER['SCRIPT_NAME'] on any given page, I can see it does match up correctly (it matches a page specified in the array, for example, /admin/update.php as expected) and so I know the values in the array are in the correct format.
What am I doing wrong?
Based on the example provided, I can't see any way that myCoolFunction(); can ever execute.
$_SERVER['SCRIPT_NAME'] will never be equal to $allowed_pages because the first is a string and the second is an array.
Instead of the code as presented, use a function such as in_array to verify that the SCRIPT_NAME value is in the array:
$allowed_pages = array('/admin/update.php', '/admin/system.php', '/admin/install.php');
if (in_array($_SERVER['SCRIPT_NAME'], $allowed_pages)) {
myCoolFunction();
} else {
echo 'Not found in array';
}
in_array is defined thus:
Checks if a value exists in an array
More information about in_array is in the official docs.

How to match a variable with value in double array

i have a problem like the following sample code :
$code='100'; //$maybe $code='0' or $code='1' ... i just set a number as an sample
$xx=array(
'0'=>array(a,b,c),
'1'=>array(d,e,f),
........
'100'=>array(aa,bb,cc)
);
I want find $code in array :
if($code==$xx['$code']){
echo $xx['code'][0]; //if i want get the value 'aa'
}
But it seems like $xx['$code'] doesn't work.
Do anyone know the right way to solve it?
Firstly you need to use array_key_exists for getting within if condition and then after you can use it simply like as
if(array_key_exists($code,$xx)){
echo $xx[$code][0];
}
or can simply use isset instead like as
if(isset($xx[$code])){
echo $xx[$code][0];
}
you shouldn't use single quotations here,
when filling displaying a variable either use without quotations or put it between double "" try $xx[$code] or $xx["$code"]
Use isset OR !empty to check key exist in array or not. It will also check that key has valid value.
if(isset($xx[$code])){
echo $xx[$code][0];
}
OR
if(!empty($xx[$code])){
echo $xx[$code][0];
}
if($code==$xx['$code']){
echo $xx[$code][0]; //if i want get the value 'aa'
}
If you use '$code' the content of $code will not be checked as '' interpret everything as a string and won't look a variables in it.
You can't sace 'code' either, as code is only the name of the variable you use.

PHP array element comparison

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

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