Checking a value if in array - php

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

Related

How to convert strings to 2D array in php?

I have 2 strings which returns me the url and status from a curl call. I want to combine these two strings and create an array so that I can convert back to json object to fetch it in the twig.
I have tried using the explode() and the array() function.
$url =
"'http://www.testsite.com','http://www.google.org','http://www.fb.net'";
$status = 200,300,404;
var testArray = array($url,$status);
I want to make my array look like :
testArray[0][$url] = http://www.testsite.com and
testArray[0][status] = 200
Explode both strings, then loop over them and push an associative array with the values onto the result array.
$testArray = [];
$url_array = explode(',', $url);
$status_array = explode(',', $status);
foreach ($url_array as $i => $u) {
$u = trim($u, "'"); // remove surrounding quotes
$s = $status[$i];
$testArray[] = ['url' => $u, 'status' => $s];
}

implode value does not count as an array

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 ."];");

Make string from array in php

I've got this object
[{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]
And i want to build a string like this:
"Fressnapf","Whiskas","Purina"
But if the one of the isChecked boolean would be (false for example like this: [{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":false},{"name":"Purina","isChecked":true}] )
then the string should be look like this:
"Fressnapf","Purina"
So i have a $brands object ( json form above) and now what?
// Decode json to PHP array json_decode(<JSON>, true) the second parameter converts to array instead of object
$arrays = json_decode('[{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]', true);
// Create an array to store the output data you want
$checked_names = [];
// Loop through the arrays of properties in your JSON to find out if the value isChecked is true and if so add the name to your checked_names array
foreach ($arrays as $array) {
if (!empty($array['isChecked'])) {
$checked_names[] = $array['name'];
}
}
// Output with surrounding quotation marks.... implode will turn your array into a string with "glue" -- stuff in between the items... so you need the extra quotes on the outside as well
echo '"' . implode('", "', $checked_names) . '"';
// --- Decode the json array.
$array = json_decode('[{"name":"Fressnapf","isChecked":false},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]');
$string = array();
// --- Loop through the array.
foreach($array as $item){
// --- Check to see if item is checked. If it is, stick it into array $string.
if($item->isChecked != false){
$string[] = $item->name;
}
}
// --- Transform $string to an actual string.
$string = implode(', ', $string);
echo $string;

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.

PHP in_array isn't finding a value that is there

I have an array called $friend_array. When I print_r($friend_array) it looks like this:
Array ( [0] => 3,2,5 )
I also have a variable called $uid that is being pulled from the url.
On the page I'm testing, $uid has a value of 3 so it is in the array.
However, the following is saying that it isn't there:
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
This always returns false. I echo the $uid and it is 3. I print the array and 3 is there.
What am I doing wrong? Any help would be greatly appreciated!
Output of
Array ( [0] => 3,2,5 )
... would be produced if the array was created by something like this:
$friend_array = array();
array_push($friend_array, '3,2,5');
print_r($friend_array);
Based on your question, I don't think this is what you meant to do.
If you want to add three values into the first three indexes of the array, do the following:
$friend_array = array();
array_push($friend_array, '3');
array_push($friend_array, '2');
array_push($friend_array, '5');
or, as a shorthand for array_push():
$friend_array = array();
$friend_array[] = '3';
$friend_array[] = '2';
$friend_array[] = '5';
Array ( [0] => 3,2,5 ) means that the array element 0 is a string 3,2,5, so, before you do an is_array check for the $uid so you have to first break that string into an array using , as a separator and then check for$uid:
// $friend_array contains as its first element a string that
// you want to make into the "real" friend array:
$friend_array = explode(',', $friend_array[0]);
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
}
Working example
Looks like your $friend_array is setup wrong. Each value of 3, 2, and 5 needs its own key in the array for in_array to work.
Example:
$friend_array[] = 3;
$friend_array[] = 2;
$firned_array[] = 5;
Your above if statement will then work correctly.

Categories