how to check empty value from array? - php

OK. So i have a json_encoded string like this:
{"MostViews":"1","Tags":"","PhotoSize":""}
Decoded it so it looks like this:
$specificdetail = json_decode('{"MostViews":"1","Tags":"","CanvasSize":""}',true);
print_r(specificdetail);
// printed array
Array
(
[MostViews] => 1
[Tags] =>
[PhotoSize] =>
)
Now you can see in the array there are two items Tags and PhotoSize are empty.
and My Requirement is that:
I am creating a dynamic div which will be visible if i got item with a value. I mean item should have any value. if all have empty then i will not show the div.
So i just did the basic thing to extract the array value:
$counter=0;
foreach($specificdetail as $specificd)
{
if(!empty($specificd)){
$counter++;
}
}
if(!empty($counter))
{
echo "<div>Detail:</div>";
}
Now it is giving me this Fatal Error:
Fatal error: Cannot access empty property
And i have also tried to use key=>value pair and checked the value but same result.
Can anybody tell me whats wrong with this? I know that many questions related to this fatal error have been asked before and i have checked few of them but non of them helped me?
Please Help.

OK. so i just did a little change in my if condition and also used the key=>value pair
foreach($specificdetail as $key=>$specificd)
{
if($specificd !== '' ){
$counter++;
}
}
echo $counter; // it gives me 1 which is true because there is only one item is not empty
BTW thanks everybody to giving your precious time.

Try this instead:
if($counter != 0)

Hello just put this code
$empty=array();
$feed=array();
$k=0;
$count_feeed=0;
$count_empty=0;
foreach($specificdetail as $key=>$val){
if($val != ""){
$feed[$k][$key]=$val;
$count_feeed++;
}else{
$empty[$k][$key]=$val;
$count_empty++;
}
$k++;
}
echo "<br/> Total feeding element: $count_feed;";
echo "<br/> Total empty element: $count_empty;";
echo "Your feeding array which is not empty.";
echo "<pre>";
print_r($feed);
echo "<br/>";
echo "Your empty array which is empty.";
echo "<pre>";
print_r($empty);
echo "<br/>Enjoy....";
Let me know if any bug

first json decode your code with json_decode() function then ,
$old_count=count($array);
$new_count=count(array_filter($array));
$number_of_empty_values=($old_count - $new_count);
echo $number_of_empty_values;

Related

PHP MYSQL ARRAY check if string is in array

I have user input which in this case will be Hello
$command = mysqli_real_escape_string($con,$_POST['command']);
a variable called $dialogue_unlock is populated through some scripts. Which for testing will output 'Hello','Goodbye'
$dialogue_unlock .= ',\''. $discuss_row['discussion_text'].'\'';
Im then trying to see if the user input matches the array
$dialogue_array = array($dialogue_unlock);
if(!in_array("$command", $dialogue_array)){
$err .= 'Invalid Question';
}
As a test im using
echo $err. '<br>';
echo $command. '<br>';
echo $dialogue_unlock;
I get
Invalid Question
Hello
'Hello','Goodbye'
I just cant wrap my head around it as 'hello' is definitely in 'Hello','Goodbye'. Can anybody offer some advise please.
Many thanks.
It looks as though your array contains the 1 element with the text 'Hello','Goodbye' and when you look for Hello it doesn't match. What you should do is add each item of $discuss_row['discussion_text'] to $dialogue_array directly using (in whatever loop you build up $dialogue_unlock)
$dialogue_array[] = $discuss_row['discussion_text'];
So when you add Hello and Goodbye then it will be two separate elements in the array.
Just make sure that before this loop you initialise the array...
$dialogue_array = [];
Try this.
$command = mysqli_real_escape_string($con,$_POST['command']); /// hello
$dialogue_unlock .= ',\''. $discuss_row['discussion_text'].'\''; /// 'Hello','Goodbye'
$dialogue_unlock = explode(',', $dialogue_unlock); /// dialogue_unlock to array
foreach ($dialogue_unlock as $a) {
if (strpos($command, $a) !== FALSE) {
echo "Match found";
}
else
{
echo "Not found!";
}
}

Multidimensional session php array echoing

I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}

How to parse a web service returned response into an array in PHP

I am updating my question with a few breakthroughs i was able to achieve today. I used get_object_vars.
This code was able to print out the value i am trying to iterate over.
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
print_r('<pre>'. print_r($arrayPid) .'</pre>');
This http://www.image-share.com/ijpg-1163-165.html is what i saw as a result.
Now since this Object has objects inside it along with the values i need i.e. FileID,FileName etc. I am seeing the error message but a glimpse of the output. The code i used was this (just a very minor change from the above. I used a foreach)
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
//print_r('<pre>'. print_r($arrayPid) .'</pre>');
foreach($arrayPid as $val) {
echo ($val);
echo "<br>";
}
}
As a result of this i saw the following output http://www.image-share.com/ijpg-1163-166.html .
The index number 1 occupies the object and hence the error for string conversion.
If i use a For loop instead of the foreach in the code just above,i am unable to print the values.
I tried:
for($i=0;$i<(count($arrayPid));$i+=1)
{
echo($arrayPid[$i]);
}
But this would print nothing.
Could any one help me with a way so that i can iterate and have the values inside that array $arrayPid.
Would like to have your suggestions, views, doubts on the same.
I am sorry that i am using imageshare but that is the only way i can share my screens.
Thanks
Angie
The correct way to use it is:
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//print_r($fileStatusObtained->FileID);
$fileId [] = $fileStatusObtained->FileID;
...
}

PHP array_search not working

can anybody let me know why array_search doesnt works for me? All i want is to search value and and get corresponding key value
for eg if i search wiliam i should get 4.. Its simple but aint working for me
<?php
$fqlResult[0]['uid']='1';
$fqlResult[0]['name']='Jay';
$fqlResult[1]['uid']='2';
$fqlResult[1]['name']='UserName2';
$fqlResult[2]['uid']='3';
$fqlResult[2]['name']='Frances';
$fqlResult[3]['uid']='4';
$fqlResult[3]['name']='William';
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname="'".$fqlResult[$i]['name']."'";
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
}
echo "<pre>";
print_r($userdb);
echo "</pre>";
echo array_search('4', $userdb);
?>
It doesn't work because array_seach searches values and "William" is a key. To complicate things, your values and keys are wrapped in single quotes during the for loop.
You'd want to do something like this:
if ( ! empty($userdb["'William'"]) )
{
// Echoes "'4'"
echo $userdb["'William'"];
}
// To find user ID "'4'"
// Outputs "'William'"
echo array_search("'4'", $userdb);
If you don't want things wrapped in single quotes, you'll need to change your for loop as follows:
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['name'];
$userdb[$userdbname]=$fqlResult[$i]['uid'];
}
if ( ! empty($userdb["William"]) )
{
// Outputs "4" (without the single quotes)
echo $userdb["William"];
}
// To find user ID "4" (without the single quotes)
// Outputs "William"
echo array_search('4', $userdb);
array_search() searches values, not keys.
If you want to check the existence of something that you use as a key in an array, you can just use isset:
if(isset($userdb['William'])) {
echo "$userdb[William] is William's uid!";
}
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['uid'];
$userdb[$userdbname]=$fqlResult[$i]['name'];
}
Change
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
with this
$userdb[$i] = "{$fqlResult[$i]['name']}";
array_search only works with arrays of scalar data. You're trying to search an array of arrays. You can easily search the array yourself:
function search_array_col($array, $col, $val)
{
foreach ($array as $key => $a)
{
if ($a[$col] == $val) return $key;
}
return null;
}
echo search_array_col($fqlResult, 'name', 'William') , "\n";
echo search_array_col($fqlResult, 'uid', '4') , "\n";
Edit: n/m, I misread your code. However, you could still use this to search your original array, so I'll leave the answer for reference.
try this:
foreach($fqlResult as $result)
{
$name = $result["name"];
$uid = $result["uid"];
$userdb[$name] = $uid;
}
then you want to use array_key_exists() to find the key. array_search() only works for searching values, not keys.
$nameExists = array_key_exists("William",$userdb);
You can remove the quotes in the $userdbname="'".$fqlResult[$i]['name']."'";
rewrite it to
$userdbname= $fqlResult[$i]['name'];

Output (echo/print) everything from a PHP Array

Is it possible to echo or print the entire contents of an array without specifying which part of the array?
The scenario: I am trying to echo everything from:
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
Without specifying "id" and instead outputting the complete contents of the array.
If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:
while ($row = mysql_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '<br />';
}
}
Or if you don't care about the formatting, use the print_r function recommended in the previous answers.
while ($row = mysql_fetch_array($result)) {
echo '<pre>';
print_r ($row);
echo '</pre>';
}
print_r() prints only the keys and values of the array, opposed to var_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types - use var_dump() over print_r().
For nice & readable results, use this:
function printVar($var) {
echo '<pre>';
var_dump($var);
echo '</pre>';
}
The above function will preserve the original formatting, making it (more)readable in a web browser.
var_dump() can do this.
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
http://php.net/manual/en/function.var-dump.php
I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.
This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.
function print_array($title,$array){
if(is_array($array)){
echo $title."<br/>".
"||---------------------------------||<br/>".
"<pre>";
print_r($array);
echo "</pre>".
"END ".$title."<br/>".
"||---------------------------------||<br/>";
}else{
echo $title." is not an array.";
}
}
Basic usage:
//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);
Results:
PETS
||---------------------------------||
Array
(
[0] => cat
[1] => dog
[2] => bird
[3] => mouse
[4] => fish
[5] => gerbil
)
END PETS
||---------------------------------||
You can use print_r to get human-readable output.
See http://www.php.net/print_r
Similar to karim's, but with print_r which has a much small output and I find is usually all you need:
function PrintR($var) {
echo '<pre>';
print_r($var);
echo '</pre>';
}
//#parram $data-array,$d-if true then die by default it is false
//#author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can use in this way....
while($row = mysql_fetch_array($result)){
p($row); // Use this function if you use above function in your page.
}
You can use print_r to get human-readable output.
But to display it as text we add echo '<pre>';
echo '<pre>';
print_r($row);

Categories