Make string from array in php - 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;

Related

Convert a string structured as a Multidimensional Array to array

I have this string:
array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));
Stored in $_POST['data']
The string Im receiving is via.load` function where the structure of the string is constructed like so.
I would like to convert it to a multidimensional array via php so I can loop through it easily
So far I`ve reached a workaround by modifying both the string and the method.
Now my string looks like this :
1,name1,1,0,|2,name2,0,1,|3,name3,0,1,|4,name4,1,1,|5,name5,1,0,|
And the method is this
$data2 = $_POST['data2']; /// get data
$data2 = substr_replace($data2 ,"", -2); // eliminate ,|
$data2 = $data2."|"; // add |
$one=explode("|",$data2); // create multidimensional array
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
I can keep this solution but I would like to know if there is another way of doing it as first requested
There is a better and simple way. You just need to use a foreach loop inside foreach loop.
$data = array(
array('1','name1','1','0'),
array('2','name2','0','1'),
array('3','name3','0','1'),
array('4','name4','1','1'),
array('5','name5','1','0')
);
foreach( $data as $d ) {
foreach( $d as $value ) {
echo $value;
echo '<br />';
}
}
You can check the online Demo
To parse your original string you can use eval()
$string = 'array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));';
eval('$array = '.$string);
But eval can/should be disabled on the server, because it comes with security issues.
What i would do is to use JSON, where you would POST the json encoding it with:
json_ecnode( $my_array );
and then decoding it:
$array = json_decode( $_POST['data'], true );

How to apply double quotes to each value in a comma-space delimited string?

I want to add double quotes of my every array.
Original value is:
192.168.183.2, 192.168.183.28
The current result is:
"192.168.183.2, 192.168.183.28"
What I want is:
"192.168.183.2", "192.168.183.28"
and here is my code:
$allowedIP = array($dScheduler['ALLOWED_IP_ADDRESS']);
echo $newarray='"'.implode('","', $allowedIP).'"';
Your input value is a string, so handle it with just one string function call (str_replace()):
Code: (Demo)
$dScheduler['ALLOWED_IP_ADDRESS']='192.168.183.2, 192.168.183.28'; // your input string
$wrapped='"'.str_replace(', ','", "',$dScheduler['ALLOWED_IP_ADDRESS']).'"';
echo $wrapped;
echo "\n\n";
// if you want an array:
$array=explode(', ',$wrapped); // generate result array
foreach($array as $v){
echo "$v\n";
}
The value delimiter in your input string is: ,, so you just need to change it to ", " and wrap the entire string in " as well.
Then you simply explode on the commas to generate your desired array of elements.
Output:
"192.168.183.2", "192.168.183.28"
"192.168.183.2"
"192.168.183.28"
Do it through a loop:
$new_array = array();
foreach($array as $a) {
$new_array[] = '"'.$a.'"';
}
It will create a new array with ", around each element.
You can use array_map
<?php
$allowedIP = array('192.168.183.2, 192.168.183.28');
$arrAllowedIP = explode(',', $allowedIP[0]);
$quotedIP = array_map(function($val)
{
return '"'.trim($val).'"';
}, $arrAllowedIP);
Try This,
$arr = ["192.168.183.2", "192.168.183.28"];
$imp = '"'.implode('", "', $arr).'"'; // to string with double quote
$exp = explode(',', $imp); // to array with double quote
echo $im;
print_r($exp);
$allowedIP = array('192.168.183.2, 192.168.183.28');
$new= implode($allowedIP);
$fl=',';
foreach (explode(',',$new) as $v){
echo '"'.$v.'"'.$fl;
$fl='';
};

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

PHP - Search array for string

I have a page with a form where I post all my checkboxes into one array in my database.
The values in my database looks like this: "0,12,0,15,58,0,16".
Now I'm listing these numbers and everything works fine, but I don't want the zero values to be listed on my page, how am I able to search through the array and NOT list the zero values ?
I'm exploding the array and using a for each loop to display the values at the moment.
The proper thing to do is to insert a WHERE statement into your database query:
SELECT * FROM table WHERE value != 0
However, if you are limited to PHP just use the below code :)
foreach($values AS $key => $value) {
//Skip the value if it is 0
if($value == 0) {
continue;
}
//do something with the other values
}
In order to clean an array of elements, you can use the array_filter method.
In order to clean up of zeros, you should do the following:
function is_non_zero($value)
{
return $value != 0;
}
$filtered_data = array_filter($data, 'is_non_zero');
This way if you need to iterate multiple times the array, the zeros will already be deleted from them.
you can use array_filter for this. You can also specify a callback function in this function if you want to remove items on custom criteria.
Maybe try:
$out = array_filter(explode(',', $string), function ($v) { return ($v != 0); });
There are a LOT of ways to do this, as is obvious from the answers above.
While this is not the best method, the logic of this might be easier for phpnewbies to understand than some of the above methods. This method could also be used if you need to keep your original values for use in a later process.
$nums = '0,12,0,15,58,0,16';
$list = explode(',',$nums);
$newList = array();
foreach ($list as $key => $value) {
//
// if value does not equal zero
//
if ( $value != '0' ) {
//
// add to newList array
//
$newList[] = $value;
}
}
echo '<pre>';
print_r( $newList );
echo '</pre>';
However, my vote for the best answer goes to #Lumbendil above.
$String = '0,12,0,15,58,0,16';
$String = str_replace('0', '',$String); // Remove 0 values
$Array = explode(',', $String);
foreach ($Array AS $Values) {
echo $Values."<br>";
}
Explained:
You have your checkbox, lets say the values have been converted into a string. using str_replace we have removed all 0 values from your string. We have then created an array by using explode, and using the foreach loop. We are echoing out all the values of th array minux the 0 values.
Oneliner:
$string = '0,12,0,15,58,0,16';
echo preg_replace(array('/^0,|,0,|,0$/', '/^,|,$/'), array(',', ''), $string); // output 12,15,58,16

How to create a string that contains the keys of a given array in PHP?

I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);

Categories