How to Check if Multi-Dimensional Associative Array is Empty - php

I have an array as follows:
$list_array = array();
$list_array[] = array (
'id' => 1,
'name' => 'Sean',
'codename' => 'Maverick'
);
$list_array[] = array (
'id' => 2,
'name' => 'Matt',
'codename' => 'Diesel'
);
$list_array[] = array (
'id' => 3,
'name' => 'Bonnie',
'codename' => 'Princess'
);
I am trying to figure out how I can check to see if it's empty. I look on the site and tried a couple of things, but it's not working. Here are the things I've tried.
Attempt 1:
if (empty($list_array)
echo "Array is empty";
Attempt 2:
$arr_empty = true;
$arr_length = count($list_array);
echo "Length: " . $arr_length . "<br>";
for ($z=1; $z<=$arr_length; $z++)
{
$arr_length2 = count($list_array[$z]);
echo $z . " Length2: " . $arr_length2 . "<br>";
if (empty($list_array[$z]))
echo $z . " Is Empty<br>";
}
I feel like I'm missing the obivious here.

There are a few PHP functions for this that all do slightly different things:
isset — Determine if a variable is set and is not NULL
Example:
if(isset($list_array)){//do something} will do something if $list_array is set to a value other than NULL.
See: http://uk3.php.net/manual/en/function.isset.php
empty — Determine whether a variable is empty. This function returns true if the variable or array is an empty string, false, array(), NULL, 0 or an unset variable. I prefer the use of the empty function.
Example:
if(!empty($list_array)){
//do something with array here, such as a foreach or while loop.
}
See: http://uk3.php.net/empty
is_null — Identifies whether or not a variable is NULL by returning either true or false. It returns true only when the variable is null. is_null() is opposite of isset(), except for one difference that isset() can also be applied to unknown variables whereas is_null() can only be used for declared variables.
Example:
if(is_null($var)){ //do something }
See: http://uk3.php.net/manual/en/function.is-null.php
Let's stick with empty:
if(empty($list_array)){ $msg = "Array is empty!"; }
if(!isset($msg)){echo $msg;}

empty should work:
if (empty($list_array))
echo "Array is empty";
else
echo "Array is not empty";
Your loop does not work because PHP arrays are zero based, you should start with zero and continue while $z < $arr_length

I found two errors in your code:
a parenthesis is not closed in Attempt 1
in your for cycle you are starting from 1 instead of starting from 0 (so, you are considering that the array will be something like array(1=>..., 2=>..., 3=>...), while it is actually array(0=>..., 1=>..., 2=>...)
So, here is your code, fixed:
$list_array = array();
$list_array[] = array (
'id' => 1,
'name' => 'Sean',
'codename' => 'Maverick'
);
$list_array[] = array (
'id' => 2,
'name' => 'Matt',
'codename' => 'Diesel'
);
$list_array[] = array (
'id' => 3,
'name' => 'Bonnie',
'codename' => 'Princess'
);
//Attempt 1:
if (empty($list_array))
echo "Array is empty";
//Attempt 2:
$arr_empty = true;
$arr_length = count($list_array);
echo "Length: " . $arr_length . "<br>";
for ($z=0; $z<$arr_length; $z++)
{
$arr_length2 = count($list_array[$z]);
echo $z . " Length2: " . $arr_length2 . "<br>";
if (empty($list_array[$z]))
echo $z . " Is Empty<br>";
}
You can try it here, with a simple copy and paste.

Related

I can print_r array value, but not check it in if statement

I'm working on a PHP function and getting this error I don't understand...
print_r($my_array); will output
Array (
[0] => Array (
[field_id_41] =>
)
)
but if I try to do
if ($my_array[0]['field_id_41'] == "some value")
I get the error
Undefined offset: 0
I've tried $my_array['0'] but that doesn't make a difference. I'm able to assign the value to another variable, and print that, but for some reason using it for the if statement breaks it.
I'm really not sure what's going on here... Any help appreciated.
EDIT: here's the actual loop I'm having trouble with
foreach($counsellors_result as $one_counsellor) {
$this_time_out_query = ee()->db->select('field_id_41')
->from('channel_data')
->where('entry_id', $one_counsellor['parent_id'])
->get();
$this_time_out = $this_time_out_query->result_array();
$time_out_status = $this_time_out['0']['field_id_41'];
if ($time_out_status != "Time Out") {
ee()->db->insert(
'relationships',
array(
'parent_id' => $entry_id,
'child_id' => $one_counsellor['parent_id'],
'field_id' => 111
)
);
}
}
try this way its help full
<?php
$this_time_out=array (0 => array ( 'field_id_41' =>""));
$time_out_status = $this_time_out[0]['field_id_41'];
if($time_out_status != ""){
echo $time_out_status;
}else{
echo "no any value<br><br>";
}
//print "no any value"
$this_time_out=array (0 => array ( 'field_id_41' =>"test"));
$time_out_status = $this_time_out[0]['field_id_41'];
if($time_out_status != ""){
echo $time_out_status;
}else{
echo "no any value";
}
//print "test"
Did you var_dump in every loop iteration? I can guess that you get array(array('field_id_41'=>'')) in the first iteration but null in the second iteration. When you look at the output you can't see var_dump(null).
Please try to dump it that way:
$i = 0;
foreach (...) {
//...
var_dump(array('i' => $i, 'var' => $time_out_status));
$i++;
//...
}
You'll probably see that in the second iteration you get:
array('i' => 1, 'var' => null)

Compare single array value

How can I do a comparison when my array returns value with index.
Returned value is Array ( [isMember] => 0 ) and I want do to a comparison on the value only
if ($memberStatus == 0)
{
print_r($memberStatus);
}
Explanation
Index Array's value can be access by using corresponding index value where as an Associative Array's value can be access by using corresponding key along with array name and in between square brackets that is
arrayName["index-value"]
or
arrayName["key-name"].
You may refer to the following code.
Code
//For Associative Array
$arrayOne = array(
'keyone' => 'a',
'keytwo' => 'b',
'keythird' => 'c'
);
if ($arrayOne['keyone'] == 'a') {
print_r($arrayOne['keyone']);
//output a
}
OR
//For Index Array
$arrayOne = array('a', 'b', 'c');
if ($arrayOne[0] == 'a') {
print_r($arrayOne[0]);
//output a
}
If you have an array like this:
$data = [ 'isMember' => 0, 'data1' => 1, 'data2' => 2 /* ... */ ];
You can access single elements by using the name of the array and write the key in square brackets:
// change isMember to whatever key-value pair you need
$memberStatus = $data['isMember'];
if ($memberStatus === 0)
{
print 'user is a member';
}
else
{
print 'user it not a member';
}
I think what you are looking for is:
$myArray = array(
'isMember' => 0
);
if ( $myArray['isMember'] == 0 ) {
print_r($myArray['isMember']);
}
Are you looking for a key inside an array? Then you need:
echo array_key_exists(9, [1=>'nope',2=>'nope',3=>'nope',9=>'yah']) ? 'Yes it does' : 'it doesn\'t';
Otherwise you are looking for:
echo in_array("my value", ["my value", "a wrong value", "another wrong one"]) ? 'yush' : 'naaaaah';
Either way you can use both in a if statement rather than a thernary operator.
I am not sure which type of array you need to compare because there are generally 2 different types of them:
Indexed
- You pick numerical index which do you want to compare
$array = array("admin", "moderator", "user");
if ($array[0] == "user") {
// CODE
}
Associative
- You pick the string key which do you want to compare
$array = array( "id1" => "member", "id2" => "not member","id3" => "user");
if ($array["id2"] == "not member") {
// CODE
}

PHP: How to output the key itself when an array item is passed to a function?

Given array item $array["first level"]["second LVL"], how can I get the key string second LVL itself, not the key-value-pair value?
More Detailed Example
I have an array item variable $array["address"]["city"] that I am passing to a function like so:
<?php
printKey( $array["address"]["city"] );
function printKey( $array_item ) {
return "Output: " . keyValue(array_item);
}
?>
How can I get the key value string city itself from the array item $array["address"]["city"]?
I've seen array_search(), array_keys(), and key(), but none seem to do the trick without a for loop at the least.
EDIT / Clarification:
The problem is, for example, sometimes my function is passed $array["address"]["name"] and sometimes it passes $array["address"]["company"].
I need to be able to dynamically output Name: or Name:
Example function:
$array["address"]["name"] = "Andre";
$array["address"]["company"] = "StackNot";
function printITEMkeyAndValue( $arrayITEM ) {
//It's not possible to do a for loop on just an item, right? It's just a string (?)
return $array_item_key . ": " . $array_item_value;
}
echo printITEMkeyAndValue( $array["address"]["name"] );
echo printITEMkeyAndValue( $array["address"]["company"] );
Desired output:
Name: Andre
Company: StackNot
I understand what you want, but see when you call printKey function with a 2 value, it is not possible to find a key, because array does not exist in the function, the solution is to send the array and your item into the function and find it by search and then get the key.
<?php
$array["address"]["city"] = 2;
function printKey( $array, $item ) {
foreach($array["address"] as $key =>$value){
if ($value == $item){
return "Output: " . $key;
}
}
}
echo printKey($array, $array["address"]["city"]);
See this example
You will have to loop through the entire array to find match with value and get the key for that value using key($array) method
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
In case of 2D array you should pass level 1 element of 2D array.
See if you can do something like this
$arr1d= $array["address"];
while ($val_name = current($array)) {
if ($val_name == '$array_item') {
echo key($array).'<br />';
}
next($array);
}
I think you already passed in second level array key in function
echo printITEMkeyAndValue( $array["address"]["name"] );
so try this if this helpful for you.
function printITEMkeyAndValue( $address, $field_name ){
if( array_key_exists( $field_name, $address ) )
return ucfirst($field_name) .': '.$address[$field_name];
}
$address = array( 'address' => array(
'name' => 'My Name',
'city' => 'My city',
'state' => 'My state',
));
echo printITEMkeyAndValue( $address['address'], 'name' );
echo printITEMkeyAndValue( $address['address'], 'city' );
echo printITEMkeyAndValue( $address['address'], 'state' );
Simply no loop need.

Using an array value to retrieve from another array

I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?

check if a value exists in array

I am trying this code to check if a value exists in an array.
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo (array_key_exists($num, $arr)); //show the index, in this case 1
}
What i want is show the correspondent value, in other words, 0.58
How can i do that ?
What you need is this:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}
Assuming that you have the key or index position of the value you want, there are two functions that you could use, array_key_exists() or isset().
array_key_exists() checks an array to see if the key you specified exists within the array. It does not check to see if there is a value associated with this key. In other words the key may be set in the array, however the value could be null.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}
isset() can be used to see if a value is set in a specific array index.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (isset($arr[$num])) {
echo $arr[$num];
}
Since you seem to be asking to only check to see if a specific value exists within an array, you can take a look at using in_array() which will scan the values of the array and return true or false depending on if it found the value.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$needle = '0.58';
if (in_array($needle, $arr)) {
echo "found: $needle";
}
Additionally, php.net has a lot of other array functions that you should familiarize yourself with.
var_dump(in_array(0.58, $arr)); // 3
relevant docs.
Try it
<?php
$arr = array(
'2' => '0',
'3' => '0.58'
);
$num = 3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
// 0.58
}
echo '<br/>';
$val = '0.58';
if (in_array($val, $arr)) {
echo '0.58 found';
}
?>

Categories