I have 2 blocks of code....
// 1st block
<div id="a1">
<?php
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
2nd block
<div id="a2">
<?php
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
Either 1st or 2nd Block will give empty results in a day. Means if Today , 1st block will give empty result & tomorrow 2nd Block will give empty result.... Alternatively....
Issue :
Today, Value is empty for 2nd block , it gave Notice: Undefined variable: new_array error , so I initialized this before 2nd block of code :
$new_array='';
it worked fine.... but tomorrow 2nd block code will give this result :
Warning: Illegal string offset ,
Fatal error: Uncaught Error: Cannot use string offset as an array
So i need to remove this code : $new_array=''; before 2nd block & i need to place before 1st block.....
What about to use if (isset($new_array)) {...} or to initialize it like array, $new_array = [];
You can add isset to other checks, like this:
if (isset($new_array) && (is_array($new_array) || is_object($new_array))) { .... }
More info about isset()
You can use isset() function to check if $new_array is set or not. Edit your code as below
// 1st Block
<div id="a1">
<?php
if(isset($new_array)){
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
}
unset($new_array);
?>
</div>
// 2nd Block
<div id="a2">
<?php
if(isset($new_array)){
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
}
unset($new_array);
?>
</div>
You are looking for isset()/empty() and perhaps a short if/else.
Example:
<div id="a1">
<?php
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
Let's say $new_array is not set/not an array/not and object. Your if statement will not continue, because it will receive false.
In case you wish to always execute your code you could do something like this: (see the notes for explanation).
<div id="a1">
<?php
$new_array = []; // [] = short for array();. $new_array will now always be an array.
// You could also do something like this:
$new_array = (! is_array($new_array)) ? $new_array = [] : $new_array; // Here you say $new_array is always set with his code and else it will be an empty array.
if (is_array($new_array)) //
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
http://php.net/manual/en/control-structures.if.php // Shorthand if/else
http://www.php.net/manual/en/function.is-array.php // is_array
You can check first if array exists or not. If it exists then check if it is empty(if it is an array) or count the number of elements in it is greater than zero (in case of object array)
<div id="a1">
<?php
if (is_array($new_array) || is_object($new_array)) {
if (isset($new_array)) {
if (empty($new_array) || count($new_array) > 0) {
foreach ($new_array as $name => $val) {
echo $name . " : " . $val[0] . " , " . $val[1] . " , " . $val[2];
}
}
}
}
unset($new_array);
?>
</div>
data type mismatch in php 7 result in this error.
instead of
$new_array='';
Initialize like
$new_array=array();
Once you unset it destroys that array. So intialize that before first block code
Related
I have a function that prints "Our data" first and then inside a loop checks for all the data in the database and then prints the data.
However, if there is no data, it shouldn't print "Our data", how do I achieve this since "Our data" is already printed?
The layout is as follows :
<h1> Our Data </h1>
<p> <!-- DATA --> </p>
The function is as follows:
function cpt_info($cpt_slug, $field_name, $title) {
echo "<h1>Our" . $title . "</h1>"; //here I want to print our data
$args = array('limit' => -1);
$cpt = pods($cpt_slug, $args);
$page_slug = pods_v('last', 'url');
echo "<h1 class='projects-under-" . $cpt_slug . "'>" . $title . "</h1>";
if ($cpt->total() > 0) :
while ($cpt->fetch()) :
if (!strcasecmp($cpt->field('post_name'), $page_slug)) :
$data = $cpt->field($field_name);
foreach ((array) $data as $key => $value) {
if ($value != null) : //here I check whether data is empty
$url = wp_get_attachment_url(get_post_thumbnail_id($value['ID']));
echo "<div class='col-sm-3 col-xs-6'><div class='border-to-circle'>";
echo "<div class='circle-container' style='background: url(" . $url . ")center center, url(" . get_template_directory_uri() . '/images/rwp-banner.jpg' . ")center center;'><h4><a href='" . get_permalink($value['ID']) . "'>" . $value['post_title'] . "</a></h4></div>";
echo "</div></div>";
endif;
}
endif;
endwhile;
endif;
}
Something like below:
if(count($data)){
echo '<h1> Our Data </h1>';
}
I have a order form with inputs like this:
<input type="text" name="booking[Sandwich][Roastbeef][qty]" />
<input type="text" name="booking[Sandwich][Cheese][qty]" />
<input type="text" name="booking[Pizza][Classic][qty]" />
<input type="text" name="booking[Pizza][Special][qty]" />
<input type="text" name="booking[Coffee][qty]" />
I'm having trouble looping through the arrays correctly.
Here is what kind of output I would like to have:
<h2>Sandwich</h2>
<p><strong>Roastbeef:</strong> 10</p>
<p><strong>Cheese:</strong> 5</p>
<hr>
<h2>Coffee</h2>
<p><strong>Quantity:</strong> 15</p>
If all the pizza input is empty, the heading "Pizza" should not be printed! The same with the "coffee" or "Sandwich" group. If the order does not contain anything in the group, the heading should not be printed.
I can't write specific tests for every input, as I have 200 of them.
Here is what I have tried to do:
$booking = $_POST['booking'];
//First check if there is one or more input that is not empty
if (!empty($booking)) {
foreach ($booking as $type => $items) {
if (count(array_filter($items))) {
$order .= "<hr>\n<h2>" . ucfirst($type) . ":</h2>\n";
}
foreach ($items as $name => $qty) {
if ($qty > "0"){
$order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qty . "</p>\n";
}
}
}
}
This code only works when the array has a length of two keys. I can't seem to wrap my brain around as how to deal with other lengths. Any help would be great!
Edit:
With the answer from #treegarden, I have almost what I need. Now I just need to have some sort of check if the "group" is empty, then the <h2> should not be printed. if (count(array_filter($entry))) works in not printing any thing if the group is empty, but just for those input that only have two keys.
if (!empty($booking)) {
foreach($booking as $key=>$entry) {
if (count(array_filter($entry))) {
echo "<h2>$key</h2>"; //Should only be printed if one or more inputs in the group are not empty
foreach($entry as $key=>$subEntry) {
if(is_array($subEntry) && $subEntry['qty'] > 0) {
echo "<p><strong>$key:</strong>" . $subEntry['qty'] . "</p>";
} elseif(!is_array($subEntry) && $subEntry > 0) {
echo "<p><strong>Quantity:</strong> $subEntry</p>";
}
}
echo '<hr/>';
}
}
}
Maybe try recursion, from example snippet:
<?php
class RecursiveArrayOnlyIterator extends RecursiveArrayIterator {
public function hasChildren() {
return is_array($this->current());
}
}
?>
else a simple forward way is to assume you have three or more nested loops,
keep checking is $value in $kv using is_array(), which is done by invoking a function.
Try this
$booking = $_POST['booking'];
if (!empty($booking)) {
foreach ($booking as $type => $items) {
if (count(array_filter($items))) {
$order .= "<hr>\n<h2>" . ucfirst($type) . ":</h2>\n";
}
foreach ($items as $name => $qty) {
if (is_array($qty)) {
foreach ($qty as $qt) {
if ($qty > "0"){
$order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qt. "</p>\n";
}
}
} else {
if ($qty > "0"){
$order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qty . "</p>\n";
}
}
}
}
}
Im getting Parse error from:
$uphalfh = if(isset($price30in)) { echo $price30in->textContent;}
if(isset($price30out)) { echo ", " . $price30out->textContent; }
How can I improve this code to avoid Parse error? I understand that I can't use IF statement in $var
When I Echo Variable's its works like a charm and I get the results that I want. But how can I assign the result of Echo Variable's (on Line:10) to $uphalfh
include_once './wp-config.php';
include_once './wp-load.php';
include_once './wp-includes/wp-db.php';
// A name attribute on a <td>
$price30in = $xpath->query('//td[#class=""]')->item( 1);
$price30out = $xpath->query('//td[#class=""]')->item( 2);
// Echo Variable's
if(isset($price30in)) { echo $price30in->textContent;} if(isset($price30out)) { echo ", " . $price30out->textContent; }
// The wrong CODE i tried:
// $uphalfh = if(isset($price30in)) { echo $price30in->textContent;}
// if(isset($price30out)) { echo ", " . $price30out->textContent; }
// Create post object
$my_post = array();
$my_post['post_title'] = 'MyTitle';
$my_post['post_content'] = 'MyDesciprion';
$my_post['post_status'] = 'draft';
$my_post['post_author'] = 1;
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
update_post_meta($post_id,'30_min',$uphalfh);
$uphalfh = isset($price30in);
if(isset($price30in)) {
echo $price30in->textContent;
}
if(isset($price30out)) {
echo ", " . $price30out->textContent;
}
remove the assignment.
if(isset($price30in)) { echo $price30in->textContent;}
if(isset($price30out)) { echo ", " . $price30out->textContent; }
// $uphalfh = you have to complete the variable initialising here and then continue with the conditional statement or remove the variable initialising and continue with the conditional statement because $var = if(conditon){ }else{ }; is wrong syntax in php
if(isset($price30in)) {
echo $price30in->textContent;
}
if(isset($price30out)) {
echo ", " . $price30out->textContent;
}
echo $uphalf = (isset($price30in)) ? $price30in->textContent : "";
The if clause does not return a value, which means you can't use it in the context of assigning a value to variable because there is no value to be had.
$uphalfh = if(isset($price30in)) {
echo $price30in->textContent;
} if(isset($price30out)) {
echo ", " . $price30out->textContent;
}
The above code will not work as you expected it, the bellow code should work as expected -- the value of $uphalf will be set to either $price30in->textContent or $price30out->textContent.
if(isset($price30in)) {
$uphalfh = $price30in->textContent;
} if(isset($price30out)) {
$uphalfh = ", " . $price30out->textContent;
}
Only if you also want this result to be outputted to the browser (directly visible to a visitor) you could use echo.
if(isset($price30in)) {
$uphalfh = $price30in->textContent;
}
if(isset($price30out)) {
$uphalfh = ", " . $price30out->textContent;
}
echo $uphalfh;
A simple edit did the trick! That solved my problem :-)
I replaced:
$uphalfh = if(isset($price30in)) { echo $price30in->textContent;}
if(isset($price30out)) { echo ", " . $price30out->textContent; }
With this:
$uphalfh = $price30in->textContent. ', ' . $price30out->textContent;
I have the following code with the if...else statement within a while loop.
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$nextcolr = next($colour);
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
I can't work out why what ever is in the else statement isn't being executed, even if I switch the two statements and reverse the operator. Could anyone help me?
The entire while loop:
while($row = mysql_fetch_array($result))
{
echo "by <a href='/neuro/profile.php?userid=$row[MemberID]'>" . $row['FirstName'] . " " . $row['LastName'] . "</a> on " . $row['Timestamp'] . " | " . $row['NumberOfComments'] . " comments.";
echo "<div id='blog' style='background-color:#";
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
echo "'><a href='blog.php?threadid=" . $row['tID'] . "'>" . $row['Title'] . "</a></div>";
}
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
while ... {
$nextcolr = next($colour);
if ($nextcolr === FALSE)
{
reset($colour);
}
echo current($colour);
}
is how your while loop should look like. If I am right, you are also defining $colour in the while loop, which might cause problems.
If all this is in the while loop, then you are re-declaring the array on each iteration, thus returning the array internal pointer to the beginning with each iteration.
If you want to iterate this array multiple times, you could do it this way:
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$i = 0;
while ... {
...
echo $colour[$i++ % count($colour)];
...
}
So you don't need this if-else block.
The problem with your original while loop is that you never change the value of $nextcolr.
Thus, it always remains FALSE and the else part never gets executed.
I am trying to process a form that is dynamically created and therefore varies in length. The while loop seems to work fine. However, the 'if' statement is not; it should only print the startId$i and corId$i if and only if the form's particular text field was filled in. The code is printing a line for every text field on the form, regardless of if it was left empty or not.
$i = 0;
while(!is_null($_POST["startId$i"])){
if(($_POST["startId$i"]) != ""){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
$i = 0;
while(isset($_POST["startId$i"])){
if( !empty($_POST["startId$i"]) ){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
Can you manage with fields names ?
If yes, better way is to name inputs with name="startId[0]" and name="corId[0]" and so on...
Then in PHP you just do:
$startIds = $_POST['startId'];
$corIds = $_POST['corId'];
foreach ( $startIds as $k => $startId ) {
if ( !empty($startId) ) {
$corId = $corIds[$k];
echo "startId: " . $startId . " ---<br>";
echo "corId: " . $corId . " ---<br>";
}
}
You should use empty() in this case:
if(!empty($_POST["startId$i"])) {
...
}
I suggest to check the real content of $_POST. You can do that via var_dump($_POST);
You may find out, for example, that the empty fields contain whitespaces. In that case the trim() function may help.
For example:
while(isset($_POST["startId$i"])){
if(trim($_POST["startId$i"])){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}