php variable in an array - php

$q2=$_REQUEST['binge'];
'book2'=>array('callno'=>123006,'price'=>number_format(844,2),'desc'=>'Binge','auth'=>'Tyler Oakley','quant'=>$q2,'total'=>number_format(844,2)*$q2)
On this particular code, It kept displaying errors like this
Warning: A non-numeric value encountered in C:\xampp\htdocs\Webcard_3new\Webcard\wishlist.php on line 97
I searched all over the net for finding the right answers but some are just so complex to understand...
It supposed to be that $q2 is the variable inside an array. That variable is then multiplied to the "TOTAL". but the errors kept on going.. please help!!

The super-globals will always be strings. You need to explicitly convert them using intval():
$q2 = intval($_REQUEST['binge']);
Also, this line:
'book2'=>array...
Should be
$book2 = array...

You can use
$q2 = filter_var($_REQUEST['binge'], FILTER_VALIDATE_INT);
here you will have the benefit of validation where false is returned when someone passes a value that is not an integer. If it is instead a float use FILTER_VALIDATE_FLOAT instead.
Also, consider using $_GET, or $_POST directly to have more control of the data channel. $_REQUEST cobbles together several things into one, which sometimes may cause issues when more than one channel have the same key.

Related

Warning: Attempt to read property "[ARRAY KEY]" on null in PHP

$pairs = []; // Clear the pairs array
$pairs['post_name'] = $post->post_name; // Hold the post_name for the error function's use
$pairs['post_id'] = $post->ID; // Hold the post ID for the error function's use
$pairs['tag'] = $tag; // Add the tag to the pairs array for the error function's use
The above is code to define an array then set a few values. This is throwing an error that I suspect is complaining because I didn't pre-define the keys, but I also don't want to. One of the biggest advantages of PHP is that it's not necessary to pre-define and allocate every little thing when it's obvious from context.
Is there a simple way of solving this problem without having to predefine the entire array and all it's keys? I tried changing the definition to $pairs = {} on the hopes it would be happier, but no dice. I suspect this is a problem with updating to PHP 8 and am tempted to turn off warnings, but would rather do it "right" (unless that means predefining everything).
EDIT: TO be clear, the error listed in the title applies to ALL of the above assignments and any other similar assignments in my code. I'm getting a hundred or more instances of this error because I've always created array keys on assignment like this before and I'd like to keep doing so.

Do I need to initialise every key of a multidimensional array in PHP?

stricly speaking / best practice: do I need to set up every 'deeper nested sub array' or can you just access it?
//so do I need to do this:
if(!isset($multiArray[$newKey])) $multiArray[$newKey] = array();
//before I can do this?
$multiArray[$newKey][] = 'somevalue';
Strictly speaking no, PHP will create the new array before pushing the value to it, without any problem.
Best practice? It's probably personal opinion based, I would say create the array first for readability and it makes sense logically. If another developer picks up your code, it might not be obvious that you are creating a new array, as opposed to pushing to an existing array.
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.
Source : PHP Manual http://fr2.php.net/manual/en/function.array-multisort.php

$data = array() vs unset($array)

this is my first question.
I am doing some optimizations on a php script, improving its speed of execution...
Between :
$datas = array();
$datas['file_import'] = $file_name_reporting;
And :
unset($datas);
$datas['file_import'] = $file_name_reporting;
Can someone tell me which one is faster ?
Thank you
Your second example causes warning, because $datas is right now null and you are treating it as an array, so you have to declare it as an empty array before.
So just follow your first example - assign an empty array and then put into it some data.
array() will create an array whereas unset() will destroy a variable.
I think first method is just a overwriting but second one includes deleting, checking existence, triggering warning and creating new array
It's ridiculous to claim that either form is "faster" than the other. Both versions will execute so fast that you would need to run them millions of times inside a loop to perhaps notice a difference. Do you actually do that inside your script? If not, forget about "optimization" here (actually, it would be a good idea to forget about all optimization "by eye", as any experienced developer can tell you).
On top of that, the two versions actually do different things, in that unset will remove the name $datas from the sumbol table (and give you a notice in the next line when you attempt to add a value to an array).
Just use what feels right, and look inside heavy loops to find something to optimize.
In both cases, a new Array will be constructed. Unsetting a variable in php, will set it's value to null, only to call the array constructor on the next line. Although I agree with knittl, my suggestion would be:
$datas = array('file_import' => $file_name_reporting);
By creating a new array, you automatically 'unset' the variable, and by passing values to the array constructor, you can fill your array with whatever values you want while you're at it.
Obviously the first code will work faster because you do only two operations: explicitly create an array and add a portion of data. The second example will cause a warning because you destroy a variable and then try to use it again.
Additionally unset will not release used memory, it will only release a pointer on variable. Memory will be released when gc will be runned. To release a memory, use $datas = null; instead.

Getting array param out of query string with PHP

(NOTE: This is a follow up to a previous question, How to pass an array within a query string?, where I asked about standard methods for passing arrays within query strings.)
I now have some PHP code that needs to consume the said query string- What kind of query string array formats does PHP recognize, and do I have to do anything special to retrieve the array?
The following doesn't seem to work:
Query string:
?formparts=[a,b,c]
PHP:
$myarray = $_GET["formparts"];
echo gettype($myarray)
result:
string
Your query string should rather look like this:
?formparts[]=a&formparts[]=b&formparts[]=c
If you're dealing with a query string, you are looking at the $_GET variable. This will contain everything after the ? in your previous question.
So what you will have to do is pretty much the opposite of the other question.
$products = array();
// ... Add some checking of $_GET to make sure it is sane
....
// then assign..
$products = explode(',', $_GET['pname']);
and so on for each variable. I must give you a full warning here, you MUST check what comes through the $_GET variable to make sure it is sane. Otherwise you risk having your site compromised.

Variable in $_POST returns as string instead of array

In my form i have fields with name photoid[] so that when sent they will automatically be in an array when php accesses them.
The script has been working fine for quite some time until a couple days ago. And as far as i can remember i havent changed any php settings in the ini file and havent changed the script at all.
when i try to retrieve the array using $_POST['photoid'] it returns a string with the contents 'ARRAY', but if i access it using $_REQUEST['photoid'] it returns it correctly as an array. Is there some php setting that would make this occur? As i said i dont remember changing any php settings lately to cause this but i might be mistaken, or is there something else i am missing.
I had the same problem. When I should recieve array via $_POST, but var_dump sad: 'string(5) "Array"'. I found this happens, when you try use trim() on that array!
Double check your code, be sure you're not doing anything else with $_POST!
Raise your error_reporting level to find any potential source. It's most likely that you are just using it wrong in your code. But it's also possible that your $_POST array was mangled, but $_REQUEST left untouched.
// for example an escaping feature like this might bork it
$_POST = array_map("htmlentities", $_POST);
// your case looks like "strtoupper" even
To determine if your $_POST array really just contains a string where you expected an array, execute following at the beginning of your script:
var_dump($_POST);
And following for a comparison:
var_dump(array_diff($_REQUEST, $_POST));
Then verifiy that you are really using foreach on both arrays:
foreach ($_POST["photoid"] as $id) { print $id; }
If you use an array in a string context then you'll get "Array". Use it in an array context instead.
$arr = Array('foo', 42);
echo $arr."\n";
echo $arr[0]."\n";
​
Array
foo
$_POST['photoid'] is still an array. Just assign it to a variable, and then treat it like an array. ie: $array = $_POST['photoid'];
echo $array[0];

Categories