echo all array except where array is null - php

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.

Related

Array as variable for in_array

I have a table that I am reading two columns from using PDO::FETCH_KEY_PAIR. I then need check if a value from another query exists in the array returned by the PDO fetch. To illustrate:
$id = array();
/* array returned by PDO::FETCH_KEY_PAIR query */
$mailTo = array (
'MailTo1' => 6143,
'MailTo2' => 6137,
'MailTo3' => 6137,
);
echo $mailTo['MailTo1']; //6143
$result1['needle'] = 'MailTo1'; //needle from second query to seek
if(in_array($result1['needle'], $mailTo)){
$id['mailTo'] = $mailTo[$result1['needle']]; //null
}
using variable $result['needle'] returns null, but to verify that in_array returns the correct element I have used:
if(in_array('MailTo1', $mailTo)){
$id['mailTo'] = $mailTo[$result['needle']]; //6143
}
Hard coding the needle returns the correct element. Taking the needle out an array and passing as a simple variable also returns null, i.e.
$result = 'MailTo1';
if(in_array($result1, $mailTo)){
$id['mailTo'] = $mailTo[$result1]; //null
}
I cannot figure out why passing the needle as a key=>value variable ($result1['needle']) fails. It seems like this is very common practice...
In order to compare keys you need to use array key exists. in_array only looks at values and not the keys.
array_key_exists("MailTo1",$mailTo)
Another approach would be to get all keys in one array and then you can use in_array()
$mailToKeys = array_keys($mailTo);
in_array("MailTo1", $MailToKeys)
DOH!!! Wrong approach.. array_key_exists is what I should have been using!!

Count the number of "columns" in an array (php)

I have the following JSON:
[
{
"0":"2019-08-31",
"1":"Bank Exp.",
"2":"AED",
"3":"30",
"4":"",
"5":"BANK FEE 10"
},
{
"0":"2019-08-31",
"1":"Inventory",
"2":"AED",
"3":"122",
"4":"",
"5":"DEPOSIT 10000"
},
{
"0":"2019-08-31",
"1":"Petty Cash",
"2":"AED",
"3":"4999",
"4":"",
"5":"DEPOSIT 10000"
}
]
I am trying to Count the number of elements or columns in the Json. The result should be 6.
I have tried with echo count($data_array); (or sizeof) result is 3 (number of rows). How can I count the "columns" in this Json, taking into account that I must set as number of column the Max number of column a specific row has?
Do I have to use a loop to count or can I do it with a single instruction?
Assuming that some var $json contains the JSON code you have above, you should be aware that the following code will result in an array of objects of type stdClass:
$data_array = json_decode($json);
So $data_array is in fact an array, but it contains objects. As you pointed out, this will return the number of rows in your JSON:
echo sizeof($data_array);
Clearly, the number of columns is not the number of rows. If you want to know the number of columns then you'll need to check one or more rows/objects/elements of your $data_array var. It's expedient to just look at the first element:
$col_count = sizeof($data_array[0]);
HOWEVER, this is going to cause an E_WARNING if $data_array's elements are objects of type stdClass:
PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable in /tmp/foo.php on line 33
You could optionally use the second parameter of the json_decode function which will force PHP to decode every curly bracketed object in your JSON code as an associative array instead of stdClass objects:
$data_array = json_decode($json, TRUE);
$col_count = sizeof($data_array[0]);
This yields a $col_count value of6 which is the correct for the first object in your array. You should consider that later elements in $data_array may have either more or fewer columns, depending on the structure of your data. If you are sure that all elements will have the same number of columns, this is adequate, but if you have messy data, you may need to check every element of your data array to see what the true number of columns is:
$data_array = json_decode($json, TRUE);
$col_count = 0;
foreach($data_array as $row) {
$col_count = max($col_count, sizeof($row));
}
var_dump($col_count);
This will yield a $col_count value which reflects the maximum number of columns encountered in any element of your JSON. Clearly, there may be performance considerations if your JSON contains a large number of elements. It all depends on your JSON data and the nature of your application.
EDIT:
Instead of an explicit foreach loop, I think you can get away with this, but it will still require PHP to loop through your data structure. That said, it'll probably be faster:
$max_col_count = max(array_map("count", $data_array));
count($data_array) counts the number of elements in an array. In your case, is 3. But your array is multidimensional (matrix). So you need to count on some index to get the number of columns on that position:
<?php
echo count($data_array[0]);

How to prevent octadecimal conversion of a number in 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);

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.

PHP MYSQL unserialize() issues

I have a "recruiter" table in my database which has different attributes and one of them is "Professions". "Professions" is a serialized array which I get from a multiple select form. And this works fine.
When I unserialize this attribute nothing is printed - no error, no text.
This is a code I was testing serialization with:
$sql = 'SELECT Company_name, Status, Size, Professions, Seniority_levels, Sector, Website, Location FROM Recruiter';
$query = mysql_query($sql, $con);
while($result = mysql_fetch_array($query, MYSQL_BOTH)){
$recruiters[] = array($result[0], $result[1], $result[2], $result[3], $result[4], $result[5], $result[6], $result[7]);
}
foreach($recruiters AS $recruiter){
$test = unserialize($recruiter[3]);
echo $test[0].'<br>';
}
So basically $test[0] prints nothing although the new lines are printed. Please help!
try printing the $test array and the $recruiters and the $recruiter arrays. See if the result is fine before the unserialisation of the data. If the query returns any data. Also try the while loop with mysql_fetch_assoc. Let me know of the results and if this solves the problem
test = unserialize($recruiter[3]); should become test = unserialize($recruiter[5]); since the sector field is the sixth column .
However what if somewhere in the future you might need to select rows where sectors equal smth ? serialize whont help you then so i suggest you have a look at a different implementation for the sector filed witch is called bitwize http://www.litfuel.net/tutorials/bitwise.htm
Edit
Asuming you hit the right column and the column contains a:1:{i:0;s:27: a:1:{i:0;s:27: a:38:{i:0;s:27: a:9:{i:0;s:39:, it looks like the serialized array is not fully saved in you're db, it's only part of it . So the unserialize function whont return you an array . Have a look at the length of the mysql field i assume you've set it smaller than you need so you're data is trimmed on insert/update .
Edit
a:1:{i:0;s:27: you're still missing the rest of the serialized array . s:27: means a string is following containint 27 characters, and you're serialized array stops there when it should look like
a:1:{i:0;s:27:"123456789012345678901234567";}
( a:1 stands for an array containing 1 value with it's content between {}, i:0; is the array key 0, s:27:""; stands for a string containing 27 characters as the value for the i:0 key ) .

Categories