Warning: implode() [<a href='function.implode'>function.implode</a>]: Invalid arguments passed - php

if(isset($_POST['price']))
{
$ret = array();
$price= $_POST['price'];
array_push($ret,$price);
$pr=count($ret);
for($i=0; $i>$pr;$i++)
{
$pri[]=$pr[$i]*$disount/100;
echo "<script>alert('$i'); </script>";
}
$nprice = implode("," , $pri);
}
else $nprice = '0';
when data is submitted it will get $_POST['price'] . In my code i m trying apply discount on $price.As i know discount is already set . but it is giving me error ! ) SCREAM: Error suppression ignored for
Warning: implode() [function.implode]: Invalid arguments passed

Your for loop is actually wrong.. Change it to
for($i=0; $i<$pr;$i++)
//^^ <--- Do this change..
Actually it should be less than operator..
You had greater than operator and thus the condition fails , so the control flow does not go inside of your for loop, hence the $pri array obviously won't be populated and thus leading to this error.

Initialize the $pri array before the if condition
$pri = array();
Also for the for loop, if $pr is an array the condition should be something like:
for($i=0; $i<count($pr);$i++)

$pri is undefined here, so NULL. And NULL is an invalid argument to implode.
for($i=0; $i>$pr;$i++)
You seem to have used the wrong comparison sign (< vs. >), so the loop is never entered and $pri never set to be an array.
Fix that and for safety write $pri = array(); before the loop to initialize it.

Related

These errors are not resolving even there's no mistake it is not perfoming reorder

Warning: array_key_exists() expects parameter 2 to be array, string given in D:\xampp\htdocs\ecom\customer\data.php on line 45
Notice: Array to string conversion in D:\xampp\htdocs\ecom\customer\data.php on line 51
My Code
$qry = dbQuery("SELECT `orders_product`.`pd_id`, `op_quantity` FROM `orders_product`
INNER JOIN `products_detail` ON `products_detail`.`pd_id`=`orders_product`.`pd_id`
WHERE orders_product.order_id = $id");
if(dbNumRows($qry)>0) {
$cart="";
if(!isset($_SESSION['cart'])) { $_SESSION['cart']="";}
$result = dbFetchArray($qry);
while($result = dbFetchArray($qry)) {
$product_detail_id = $result["pd_id"];
$order_quantity = $result["op_quantity"];
// echo $product_detail_id;
#print_r($result);
if(array_key_exists($product_detail_id, $_SESSION['cart'])){
$quantity = $_SESSION['cart'][$product_detail_id]['quantity'] + $order_quantity;
$_SESSION['cart'][$product_detail_id]['quantity'] = $quantity;
} else {
$cart = array("pd_id"=>$product_detail_id, "quantity"=> $order_quantity);
$_SESSION['cart'][$product_detail_id] = $cart;
print_r($cart);
}
}
}
$return = 1;
echo json_encode($return);
}
First problem
Warning: array_key_exists() expects parameter 2 to be array, string given in D:\xampp\htdocs\ecom\customer\data.php on line 45
That's because you use $_SESSION['cart'] with function array_key_exists. So when a person enters the website for the first time the variable $_SESSION['cart'] is not set.
What you do then is assign an empty string.
if(!isset($_SESSION['cart'])) { $_SESSION['cart']="";}
So then you use empty string with function array_key_exists.
Solution
To resolve this issue simply change
if(!isset($_SESSION['cart'])) { $_SESSION['cart']="";}
to
if(!isset($_SESSION['cart'])) { $_SESSION['cart']=array();}
Second problem
Notice: Array to string conversion in D:\xampp\htdocs\ecom\customer\data.php on line 51
Now, this is only a notice so that's not a big issue. It may not even be something wrong. After you change to not display errors it won't affect your website in any way.
But why is this showing? Again the same reason as with the previous problem. You assign empty string to variable $_SESSION['cart'] but then you treat is as an array
$_SESSION['cart'][$product_detail_id] = $cart;
When you change the assignment from empty string to empty array this issue will be solved as well.
By the way when you write a one line if statement a good practice is not to use the braces
So I would write it like
$_SESSION['cart'] = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
Or even better
$_SESSION['cart'] = $_SESSION['cart'] ?? [];
But this is only php 7.0 and higher
I hope you understand now what was wrong and why. If you have any questions feel free to ask. I'll try to reply the best away I can.

Iterating through 3 loops of different length - PHP

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.

While loop: only Variables can be passed by reference error

I am running into a "Only variables should be passed by reference" error, because on the code I am using there is a line that does not put the explode() result into a variable. As required when using strict PHP standards.
However because the explode() function is used in a While loop I can't think of a appropriate solution.
My code looks like
function user_exists($username) {
rewind($this->fp);
while(!feof($this->fp) && trim($lusername = array_shift(explode(":",$line = rtrim(fgets($this->fp)))))) {
if($lusername == $username)
return 1;
}
return 0;
}
Any suggestions on how to solve this?
I think maybe you need to sit back and break your code apart a bit and take a look at what is happening.
First, condition is while !feof($this->fp)
From the manual:
feof — Tests for end-of-file on a file pointer
One thing you will notice here is that feof() is only a test which returns true or false. It does not advance the pointer position while looping over, so while using this function, somewhere else in your while loop there needs to be something that advances the pointer or else you will have an infinite loop.
Second condition is:
trim($lusername = array_shift(explode(":",$line = rtrim(fgets($this->fp)))))
First function from left to right is trim(), which returns a string. From our handy dandy comparison table we see that when doing if ((String) $var) it evaluates to false if and only if the string is empty ("") or the number zero as a string ("0"), otherwise it returns true. Personally I tend to really hate using if ((String) $var) (first because it's slightly unclear to newbies unless you know your comparison table well and second because 99% of the time people are doing that they are actually checking for string length, in which case I would want it to return true for the string "0"). So assuming that you don't need it to return false for "0" we could change this to strlen($var) > 0 and then manipulate the variable within the loop. That should greatly simplify things here.
So now we have:
while (!feof($this->fp) && strlen($var) > 0) { /*...*/ }
This will loop over until either we are at the end of the file or $var is an empty line. Everything else can be offloaded into the body of the while loop, so it is much easier to break apart.
So this is what we have now:
$line = rtrim(fgets($this->fp));
$lusername = array_shift(explode(":",$line)));
Uh-oh! There's that "nasty" error:
Strict Standards: Only variables should be passed by reference in /path/to/file.php on line x.
So we can see from here, the part producing the error is not explode(), but array_shift(). See also: Strict Standards: Only variables should be passed by reference
What this means is that since array_shift() modifies the array, it requires it to be by reference. Since you are not passing an actual variable but instead the result of a function, PHP is unable to modify it. It's similar to doing something like function($var) = 3;. Of course you can't do that. Instead you need to save the value to a temporary variable. So now we have:
$line = rtrim(fgets($this->fp));
$split = explode(":",$line);
$lusername = array_shift($split);
Woo hoo! No more warning message.
So putting this together, we now have:
while (!feof($this->fp) && strlen($lusername) > 0) {
$line = rtrim(fgets($this->fp));
$split = explode(":",$line);
$lusername = array_shift($split);
if($lusername == $username) {
return 1;
}
}
Also, as mentioned earlier, the fgets() will advance the pointer, which allows the !feof($this->fp) part in the while statement to vary.

Undefined Index in php array

Looking to get a count of particular key=>values in an multi dimensional array. What I have works i.e. the result is correct, but I can't seem to get rid of the Undefined Index notice.
$total_arr = array();
foreach($data['user'] as $ar) {
$total_arr[$ar['city']]++;
}
print_r($total_arr);
Any ideas? I have tried isset within the foreach loop, but no joy...
$total_arr = array();
foreach($data['user'] as $ar) {
if(array_key_exists($ar['city'],$total_arr) {
$total_arr[$ar['city']]++;
} else {
$total_arr[$ar['city']] = 1; // Or 0 if you would like to start from 0
}
}
print_r($total_arr);
PHP will throw that notice if your index hasn't been initialized before being manipulated. Either use the # symbol to suppress the notice or use isset() in conjunction with a block that will initialize the index value for you.

Illegal offset in array

I am trying to check array using another loop.
for( $i=0;$i<count($allCheckBoxId);$i++ ) {
if( $allCheckBoxId[$i] != ''){
unset( $contactlist[$cntctnum] );
}
}
I have named $allCheckBoxId, having contactnumber as value. Second array I have named $contactlist having contactnumber as key element.
For particular condition I am retrieving values of first array. Means I would have contactnumber as value retrieve in first array. IF it is not null I am unsetting second element with value contactnumber. but its giving me error on unset( $contactlist[$cntctnum] ); as Illegal offset type in unset in
Here comes interesting part.
You know, programming is not just writing the code.
Most of time programming is looking for errors. Not by asking questions on stackoverflow, but by amending your code and studying it's output and error messages. Some sort of investigation.
If you have got such an error message, doesn't that mean that somewhing wrong with offset type? Why not to print the problem variable out? just print it out:
for( $i=0;$i<count($allCheckBoxId);$i++ ) {
var_dump($cntctnum);
var_dump($allCheckBoxId[$i]);
var_dump($contactlist[$cntctnum]);
if( $allCheckBoxId[$i] != ''){
unset( $contactlist[$cntctnum] );
}
}
and see what's particularly wrong with your offset
Try casting your key into a string. Replace:
$contactlist[$cntctnum]
With
$contactlist[(string) $cntctnum]
OR
for($i = 0; $i < count($allCheckBoxId); $i++) {
if($allCheckBoxId[$i] != '') {
$key = (string) $cntctnum;
unset( $contactlist[$key] );
}
}
PHP associative arrays, as of PHP 5.4 will issue a PHP Warning: Illegal Offset Type if you use something other than a string as a key.
Furthermore, if this doesn't help, head over to the PHP Array Manual and do a Ctrl/Cmd + F for "Illegal Offset Type."

Categories