How to prevent octadecimal conversion of a number in PHP? - php

I have an array that is coming in from another system so I can't simply load the array with values as strings. In the array are IDs that are all numeric. However, some of the IDs have a leading zero and the leader zero must be there as part of the ID. PHP is converting these IDs to octadecimal. How to I prevent this so I have access to the actual ID that is in the array?
For example:
$ids=array(01234,1234);
$ids= array_map(function($var){ return (string) $var; }, $ids);
foreach ($ids as $id){
echo $id;
echo "<br />";
}
Produces:
668
1234
As you can see I've tried to convert each element in the array to a string prior to doing anything with it, but it's still coming in as octadecimal.

As #IlyaBursov said, you loose the 0 in the first line. You need to get the string version of wherever the system is getting those values. You cannot keep the leading zero if you use an integer data type.
Pass it as a string and it will maintain that leading 0.
Here is a functional example of the method described above, Run it here
$ids=array('01234','1234');
$ids= array_map(function($var){ return (string) $var; }, $ids);
foreach ($ids as $id){
echo $id;
echo "<br />";
}
Produces,
01234<br />1234<br />

The answer is to modify the string before I do anything with it, adding quotes around all the elements in the string prior to using json_decode.
$ids=str_replace(["[",",","]"],['["','","','"]'],$ids);

Related

Array to string conversion when comparing arrays [duplicate]

I am not experienced with php(i am new).
i am trying to use this code http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php to find the name of a variable, but I keep getting:
Array to string conversion for the line :
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
and also i get "only variables should be passed by reference" when I use
var_name($a, get_defined_vars());
How can I make those messages disappear? Because the entire code is working(I get the desired output).
Here is the code
<?php
function var_name (&$iVar, &$aDefinedVars)
{
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v;
$iVarSave = $iVar;
$iVar =!$iVar;
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$iVar = $iVarSave;
return $aDiffKeys[0];
}
$a=12;
echo var_name($a,get_defined_vars());
//ini_set('display_errors', '0');
?>
The Array to String conversion notice started in PHP v5.4.0. Since array_diff_assoc() doesn't search recursively, it is notifying you that it found that one of the values in your array is also an array and it had to convert it to a string.
Here's an example on how to use array_diff_assoc() for a multi-dimensional array... http://nl3.php.net/manual/en/function.array-diff-assoc.php#73972
Or perhaps switching out array_diff_assoc() for array_diff_key() would work for your purpose if you are only comparing the keys?
only variables should be passed by reference
You are passing the result of a function call as an argument. You aren't passing a variable.
$vars = get_defined_vars();
echo var_name($a,$vars);
Also, unless you're intentionally modifying one of the variables you shouldn't be passing it as a reference. That way any changes made are local to the function.

echo all array except where array is null

I am trying to echo out an array within a while statement, however, the results also include some columns from the database which may or may not be null.
Is it possible to echo all array where value is not null? I can't edit the mysql query as I need this to be dynamic as some of the columns may be used by another user.
My table contains around 20 columns, some are populated some aren't.
My code:
PHP
<?php
while($row = $mysqli_fetch_array($uploads)){
print_r(!is_null($row));
}
?>
Expected Output
Firstname: John
Lastname: Test
Age: 15
Current Output
1
Any help would be great, apologies for the lack of code.
Many possible ways. Here's one example: You could filter out the null elements and then print $row
while($row = $mysqli_fetch_array($uploads)) {
$row = array_filter($row); // 1
// or 2: $row = array_filter($row, 'strlen');
echo join(', ', $row), "\r\n";
}
this will type-cast each element to boolean and any keep those elements that evaluate to truthy. This might filter more elements than you'd like, see Converting to boolean
but you can tell aray_filter how to decide whether an element is in or out. In this case the return value of the function you give as the second parameter with be cast to boolean and checked. Using strlen an empy string and/or anything that get's cast to an empty string (like NULL) will result in 0->false->filtered out.

Function for reverse order of values in an array php

I'm new to PHP and I was asked to write a function that accepts an array as a parameter and then prints the array in reverse order. Here is what I have so far:
<?php
function RevOrder ($arr1) {
$arr1 == array();
echo array_reverse($arr1);
}
RevOrder (array(1,4,2,5,19,11,28));
?>
It is supposed to output 28, 11, 19, 5, 2, 4, 1 but I keep getting an array to string conversion error.
echo expects a string while you are passing an array, hence the array to string conversion error. It also looks like you are not properly checking if the param passed is an array. Try this:
<?php
function RevOrder($arr1) {
if (is_array($arr1)) {
return array_reverse($arr1);
}
return false;
}
$reversedArray = RevOrder(array(1,4,2,5,19,11,28));
// Option 1
print_r($reversedArray);
// Option 2
echo(implode(', ', $reversedArray));
<?php
function RevOrder (array $arr1) {
echo implode(", ", array_reverse($arr1));
}
RevOrder (array(1,4,2,5,19,11,28));
But note that this isn't particularly good design - your functions should do one thing. In this case you should instead write a function to print an array according to your liking and then pass it reversed array. Although in this case I guess it's ok to have a helper function for printing the array in reversed order but when you're doing something more complicated you should consider this.
EDIT:
You could do something like this:
function printArray(array $arr){
echo implode(", ", $arr);
}
printArray(array_reverse($arr));
As for why you can't just echo array see this
Arrays are always converted to the string "Array"; because of this,
echo and print can not by themselves show the contents of an array. To
view a single element, use a construction such as echo $arr['foo'].
See below for tips on viewing the entire contents.
Also I added type-hints for array so that when you pass something that's not an array you get an error.

Looping through json_decode with foreach loop error

I keep running into the error Warning: Invalid argument supplied for foreach() and for the life of me I can't figure out why. Here is my relevant code:
$Ids = $_POST["param-0"];
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
stripslashes($decodedJson);
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
$Ids is a string from a previous file that is encoded with json_encode. I added the stripslashes because it was recommended in another question on Stack Overflow, but it didn't help. If I change the beginning of the foreach loop to beforeach($toReturn as $id) the error goes away. Thanks!
edit: in the previous file, $_POST["param-0"] is an integer array that I returned with json_encode. With the testing data I am working with right now, ["15","18"] is what is being passed.
First you need to decode the json (which you already did)
$decodedJson = json_decode($Ids, True);
Then to grab each value from the json and, for example, echo it. Do this:
foreach ($decodedJson as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $value) {
echo $value; // This will show jsut the value f each key like "var1" will print 9
// And then goes print 16,16,8 ...
}
}
From top to botton:
$Ids = $_POST["param-0"];
This will trigger a notice if input data does not have the exact format you expect. You should test whether the key exists, for instance with isset().
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
This will return null if input data is not valid JSON. You should verify it with e.g. is_null().
stripslashes($decodedJson);
If input data was valid we'll first get a warning:
Warning: stripslashes() expects parameter 1 to be string, array given
Then, if our PHP version is very old we'll have our array cast to a string with the word Array in it, and if our PHP version is recent we'll get null. Whatever, our data is gone.
If input data wasn't valid, we'll get an empty string.
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
Neither null or strings (empty or not) are iterable. There's no nothing to do here. Our data is gone forever :_(
It ended up I was incorrectly encoding what I wanted decoded. All is well again, thanks for everyone's help!

how to save numbers only from an array into a new array

I currently have var: $_REQUEST['fb_friend_uid'] which gives me the following output:
Array{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
Im looking to save the data here into a new array, containing only the numbers in a format of; 47483647, 47483647, etc
The objective is to use it in a sql query like so:
SELECT * FROM vote WHERE
vote_fb_uid IN ($myNumbers)
Saving it into a new array I figured could be done like so:
foreach ($_REQUEST['fb_friend_uid'] as $uid) {
$uids[] = $uid['id'];
}
$ids = join(',', $uids);
However my issue remains, how to "clean" the first var to contain numbers only.
Suggestions?
I can't give you an exact solution, because I'm not sure if the value returned by $_REQUEST['fb_friend_uid'] is a PHP array printed using json_encode(), or the value is actually a json string.
In either case, where is an example which makes use of both circumstances, so use whichever one makes sense in your scenario:
If PHP Array:
Assumes PHP Array has a format similar to:
array('returned_val' => array('47483647', '47483647', '47483647', '665414807', '263901486', '665414807', '665414807', '665414807'));
<?php
$original_arr = $_REQUEST['fb_friend_uid']['returned_val'];
If JSON String:
Assumes the JSON String has a format similar to:
{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
<?php
$json_arr = json_decode($_REQUEST['fb_friend_uid'], True);
$original_arr = $json_arr['returned_val'];
Then, use this code:
<?php
// Extract only whole number values, omit anything which is not a 0-9 character.
$filtered_arr = array_filter($original_arr, 'ctype_digit');
// Escape values to remove possibility of SQL injection.
$filtered_arr = array_map('mysql_real_escape_string', $filtered_arr);
// Convert the array to a string
$string_arr = "'" . implode("','", $filtered_arr) . "'";
// Perform SQL Query
mysql_query("SELECT * FROM vote WHERE vote_fb_uid IN ($string_arr)");
Just filter the array using is_numeric:
$uids = array_filter($_REQUEST['fb_friend_uid'], 'is_numeric');
To filter for numbers you can use is_numeric( mixed $var ).
But if you need more control (only integers of certain type, length) you can either use REGEX or is_numeric and some ifs.
This looks like a json string, so use http://php.net/json_decode
Maybe you need to remove Array at the beginning (but I don't know if Array is actual in the variable), use http://php.net/substr
$jsonString = substr($_REQUEST['fb_friend_uid'], 5);
$fb_friend_uid = json_decode($jsonString);
$ids = join(',', $fb_friend_uid['returned_val']);

Categories