Simple array and simple check if is array or object .. yet page crashing when there is no array data instead of showing No. This is the array
$url=get_curl_content_tx("https://example.com");
$arr = json_decode($url, true);
if (is_array($arr['outputs']) || is_object($arr['outputs'])) {
echo 'Yes';
}
else {
echo 'No';
}
if I receive fail i.e. no data from the url and $arr['outputs'] is empty I've got blank page with
Undefined index: outputs
instead of No. Doesn't if (is_array($arr['outputs']) || is_object($arr['outputs'])) check if is array or no?
If there is data in $arr['outputs'] everything is fine.
You need to use isset or array_key_exists to check the key exists in the $arr array before referring to it.
if (isset($arr['outputs']) && is_array($arr['outputs'])) {
You want to access a non-existent array, which gives you an error, no matter what function you are using right before. To solve this, check first if the array exists with isset():
if(isset($arr)) {
// Just gets executed if the array exists ans isn't nulll
} else {
// Array is null or non-existend
}
and add then your code in the if-else.
I have 2 arrays and i want to make a 3rd array after comparison of the 2 arrays. Code is as follows:
foreach($allrsltntcatg as $alltests)
{
foreach($alltests as $test)
{
foreach($allCatgs as $catg)
{
if($catg['testcategoryid'] == $test['testcategory_testcategoryid'])
{
$catcounts[$catg['testcategoryname']] +=1;
}
}
}
}
It, although returns the right answer, it also generates a PHP error and says undefined index and prints all errors and also the right answer.
I just want to avoid the array out of bound error. Kindly help me
Problem is in if condition correct like below : You have to initialize array first and than you can increment value
if($catg['testcategoryid'] == $test['testcategory_testcategoryid'])
{
if (isset($catcounts[$catg['testcategoryname']]))
$catcounts[$catg['testcategoryname']] +=1;
else
$catcounts[$catg['testcategoryname']] =1;
}
When the array try to add some arithmetic operation of undefined index such as $catg['testcategoryname'] in the $catcounts array then the warning generates. Before add the number you have to check the index is present or not, and of not then just assign value otherwise add into it.
So do it in this way just if condition-
if(....){
if(array_key_exists($catg['testcategoryname'], $catcounts))
$catcounts[$catg['testcategoryname']] +=1; // Add into it
else
$catcounts[$catg['testcategoryname']] = 1; // Assign only
}
More about array key exists--See more
$catg['testcategoryname'] should represent an index in $catcounts array.
Is there a way to execute a code only when my array has a new value passed on in position [0];?
if(?){
print_r(array_values($parcels)[0]);
} else{}
tried multiple statements but all lead to error or invalid. If a new order comes in array[0] gets replaced with that info. So only when that info has changed execute this.. Is this Possible?
You need to store the old value in an other variable to compare it. So you are able to consider if the value has changed.
$oldValue = $parcels[0];
//-------
//Code that eventually changes the array
//-------
if($oldValue != $parcels[0]) {
print_r(array_values($parcels)[0]);
$oldValue = $parcels[0];
} else{}
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
}
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.