implode value does not count as an array - php

So this is my code for set the date from selected date to auto set date excluding weekend (sat&sun) and holiday ( i put it in database ) :
function number_of_working_dates($from, $days) {
/* get holiday from database */
include('includes/config.php');
$sss = "SELECT tanggal_awal FROM libur_nasional GROUP BY tanggal_awal ASC";
$qqq = mysqli_query($konek,$sss);
$arr = array();
while ( $tam = mysqli_fetch_array($qqq)) {
$date = $tam['tanggal_awal'];
$reformat_date = date("Y-m-d", strtotime($date));
$arr[] = $reformat_date;
}
$array_date_2 = '"'.implode('", "' , $arr) . '"';
The output of implode() is a list of dates:
"2018-08-09", "2018-08-10", "2018-08-15", "2018-08-17"
Then the continuation:
$holidayDays = [$array_date_2];
//$holidayDays = ["2018-08-09", "2018-08-10", "2018-08-15", "2018-08-17"]
$from = new DateTime($from);
$dates = [];
$dates[] = $from->format('Y-m-d');
**echo count($holidayDays);**
while ($days) {
$from->modify('+1 day');
if (!in_array($from->format('N'), $workingDays)) continue;
if (in_array($from->format('Y-m-d'), $holidayDays)) continue;
if (in_array($from->format('*-m-d'), $holidayDays)) continue;
$dates[] = $from->format('Y-m-d');
$days--;
}
return $dates;
}
When I count the "holidayDays" array using "count" it only shows 1 item, but when I hardcoded the date list like in the comment line it works and shows 4 items.
Can someone help me?

A variable containing a string contains that string and it will continue to be treated as a string unless you do something like evaluating it as source code (which is very dangerous).
So if you have:
$foo = ["1", "2", "3"];
Then you have an array with three things in it.
But if you have:
$string = '"1", "2", "3"';
$foo = [$string];
Then you have an array with one thing in it: a string.
It is the same as writing:
$foo = ['"1", "2", "3"'];
If you want to have an array of strings then look at this line of your code:
$array_date_2 = '"'.implode('", "' , $arr) . '"';
That converts the array of strings into a single string.
Do not do that because that is not what you want.
Just use the value you already have in $arr.

You have a variable named "$array_date_2" and are trying to assign a String to it with the following code :
$array_date_2 = '"'.implode('", "' , $arr) . '"';
This assignment , after the "implode" has been executed , would result in the following :
$array_date_2 = ""2018-08-09", "2018-08-10", "2018-08-15", "2018-08-17"";
Notice the quotes at the start and end of the String. Even though you do not see them when "echoing" the String is wrapped around those quotes. PHP does not permit a String without it being enclosed in quotes , it will throw a Parse Error.
So in the end you do not have a String like :
"2018-08-09", "2018-08-10", "2018-08-15", "2018-08-17"
But more like
""2018-08-09", "2018-08-10", "2018-08-15", "2018-08-17""
Now you are also trying to create an array by concatenating Strings and Special Characters together. This is not how PHP works though.
If you want to "create" a function out of a String , or generally evaluate a String as PHP Code , then you need to use "eval" but i would strongly suggest against it.
For reference only , if you went with eval your code should be like this :
eval("\$holidayDays = [".$array_date_2 ."];");

Related

Remove comma From the last value in a While loop

My main motive is to remove the comma ',' from the last value of the array.
$Followingcount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
if (mysqli_num_rows($Followingcount) > 0) {
while ($ids = mysqli_fetch_assoc($Followingcount)) {
$followedids = $ids['acc_id'].',';
$array = array($followedids);
$arraystr = implode("','",$array);
}}
If I echo $followerdids the result comes like this with commas like:
5, 7, 8,
To remove the comma at the last value I tried to place the values inside an array and then I imploded it.
When I echo $arraystr it still contains the comma at the last value.
All you need is:
$followedIds = [];
$followingCount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
while ($ids = mysqli_fetch_assoc($followingCount )) {
$followedIds[] = $ids['acc_id'];
}
echo implode(',', $followedIds);
...and take care of SQL Injection
The solution to your problem is quite simple. There is a function called rtrim(), which removes all characters on the right side.
$followedids = rtrim($followedids, ',');
There is also a trim() function, which does the same on both sides, and ltrim() which does it for the left side.
You can use rtrim to remove the last comma after the while loop.
$followedids = rtrim($followedids, ',');
You could use the substr-function (more information here)
The last parameter is the length of the substring you want, but you can also use negative values, which means "remove this many characters", in your case: 1.
In your case:
$followedids = substr($followedids, 0,-1);

Checking a value if in array

How do i correct my code ..i would like to check a value if is in array
$years[] = ''.$myyear.'';
$years_array = "array('" . implode( "','", $years) . "');";
if (in_array("2017", $years_array))
{
//do this
}
else
{
//do this
}
Your in_array with if clause looks fine, but year_array is wrong (which is string not array)
You can define year_array simply like below
$years_array = array(2015,2016,2017,2018);
OR
// Define array
$years_array = array();
// Add elements to array
$years_array[] = 2015;
$years_array[] = 2016;
$years_array[] = 2017;
In case if you have list of years as string separated by comma, then you can create array using explode() function like below
// this is string
$year_string = '2015,2016,2017,2018';
// this is array
$year_array = explode(',', $year_string);
// print string
print $year_string.PHP_EOL;
// print the contents of array
print_r($year_array);
meanwhile you can read more about arrays from here

Removing beginning and end character from String without altering array

I'm running a query to display an array. After the array is displayed I'm using that in Google Maps so the array needs to read a specific way.
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
So my array has to read array', 'array', 'array because I echo the array into the address.
var addresses = ['<?php echo $namelist ?>'];
This is my code and it outputs 'array', 'array', 'array',
$resultsearch = $con->query("SELECT * FROM db") or die(mysqli_error());
$name = array();
while ($result = $resultsearch->fetch_object()) {
$name[] = $result->name;
$namelist = substr("'".implode($name)."', ", 0, -1);
If I change the 0, -1 to 1, -2 then I'm left with array' array' array' and so forth.
I literally need the remove 1 character from the end of string and 1 character at the beginning without altering the characters of the array.
Just to add that using implode(',', $name); did not display the ',' which is why I'm trying to find a work around.
Any ideas?
Your problems are:
You use implode(); in the wrong way: right is implode("', '",$names);
substr() will not work because of wrong use of implode().
Tip: Instead of using substr() just do rtrim('value',',');
To fix your code change it to this:
$name[] = "'{$result->name}'";
$namelist = implode(', ',$name);
or this
$name[] = $result->name;
$namelist = implode("', '",$name);
And this too:
var addresses = [<?php echo $namelist ?>];
to get proper javascript/json array data.
Also works:
var addresses = <?php echo json_encode($namelist); ?>;
But here you should not add ' single-quotes to the names when collecting into an array.
Have a nice day
I ended up with $namelist = "'".$result->name."'," and then echo $namelist;
My results were addresses and believe that implode(',', $name) wouldn't work because of the results.

Remove trailing comma from line of text generated by final iteration of loop

I am creating lines of text to be consumed by another layer in my application. The lines are:
['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027],
What is the fastest/easiest way to remove the trailing comma from the last line of text?
I'm expecting something like this:
['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027]
Actual Code:
$i = 0;
while($graph_data = $con->db_fetch_array($graph_data_rs))
{
$year = $graph_data['year'];
$month = $graph_data['month'];
$count = $graph_data['count'];
$total_count = $graph_data['total_count'];
// for get last 2 digits of year
$shortYear = substr($year, -2, 2);
// for get month name in Jan,Feb format
$timestamp = mktime(0, 0, 0, $month, 1);
$monthName = date('M', $timestamp );
$data1 = "['".$monthName.' '.$shortYear."',".$total_count."],";
$i++;
}
If you have that array in a variable and want a string, you can use implode to get a string separated by a glue char.
If you already have an string, you can use rtrim to remove the last char to the right of the string.
If you have an array, where the value is a string ['Oct 13',1027] (ending in a comma), you have the same options above and:
You can use array_walk with some of the mentioned functions
You can get the last element, and use rtrim on it like the code below:
Example of code using rtrim on a array of strings:
<?php
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$lastIndex = count($values)-1;
$lastValue = $values[$lastIndex];
$values[$lastIndex] = rtrim($lastValue, ',');
<?php
$arr = array(
"['Jun 13',529],",
"['Jul 13',550],"
);
$arr[] = rtrim(array_pop($arr), ', \t\n\r');
print_r($arr);
// output:
// Array
// (
// [0] => ['Jun 13',529],
// [1] => ['Jul 13',550]
// )
Make it an actual array, and implode. Not really sure what is is going to be (if json:you can do even better and not make the values themselves fake-arrays, but this is left as an exersize to the reader).
$yourData = array();
while(yourloop){
//probaby something like: $yourData = array($monthName=>$total_count);
$yourData[] = "['".$monthName.' '.$shortYear."',".$total_count."]";
}
//now you have an actual array with that data, instead of a fake-array that's a string.
//recreate your array like so:
$data1 = implode(','$yourData);
//or use json_encode.
Something similar to #srain but using array_push.
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$last = array_pop($values); //pop last element
array_push( $values, rtrim($last, ',') ); //push it by removing comma
var_dump($values);
//output
/*
array
0 => string '['Oct 13',1027],' (length=16)
1 => string '['Oct 13',1027]' (length=15)
*/
#ElonThan was right and so was #BenFortune. This is an XY Problem, and none of the other answers are giving you the best advice -- "Never craft your own json string manually".
You think you just need to remove the final comma from your textual output so that it creates something that javascript can parse as an indexed array of indexed arrays.
What you should be doing is creating a multidimensional array then converting that data into a json string. PHP has a native function that does exactly this AND it guarantees that you will have a valid json string (because it will escape characters as needed).
I'll demonstrate how to adjust your script based on your while() loop.
$result = [];
while ($row = $con->db_fetch_array($graph_data_rs)) {
$result[] = [
date('M y', strtotime($row['year'] . '-' . $row['month'])),
$row['total_count']
];
}
echo json_encode($result, JSON_PRETTY_PRINT);
Here is an online demo that re-creates your query's result set as an input array, then replicates the loop and result generation. https://3v4l.org/cG66l
Then all you have to do is echo that string into your rendered html document's javascript where required.

Array values into string

I've been searching and searching and can't find anything that works, but this is what I want to do.
This code:
try{
$timeout = 2;
$scraper = new udptscraper($timeout);
$ret = $scraper->scrape('udp://tracker.openbittorrent.com:80',array('0D7EA7F06E07F56780D733F18F46DDBB826DCB65'));
print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
Outputs this:
Array ( [0D7EA7F06E07F56780D733F18F46DDBB826DCB65] => Array ( [seeders] => 148 [completed] => 10 [leechers] => 20 [infohash] => 0D7EA7F06E07F56780D733F18F46DDBB826DCB65 ) )
And I want that seeder count into a string such as $seeds. How would I go about doing this?
Something like this?
$seeds = $ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders'];
you can user strval() to convert a number to a string.
$string = strval($number);
or you can cast it into a string:
$string = (string)$number;
in your context that would be:
$string = strval($ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders']);
However that odd string is also the first index of the array so you could also do it like this:
$string = strval($ret[0]['seeders']);
or if you want ot use only indexes ('seeders' is also the first index of the second array):
$string = strval($ret[0][0]);
if you just want the number then it's easy too:
$num = $ret[0][0];
It's not clear if you're looking to assign the array value(s?) as a separate variable(s?) or just to cast it into a string. Here's a nice way to accomplish all the above options, by assigning each array key as a separate variable with the matching array value:
$ret_vars = array_pop($ret);
foreach ($ret_vars as $variable_name=>$variable_value) :
${$variable_name} = (string)$variable_value;
endforeach;
In your original example, this would end up populating $seeders, $completed, $leechers and $infohash with their matching string values. Of course, make sure these variable names are not used/needed elsewhere in the code. If that's the case, simply add some sort of unique prefix to the ${} construct, like ${'ret_'.$variable_name}

Categories