How to add text to array in cycle - php

I get some information from database! I need to place it on the array! How to add value to array in cycle???
I did this, but it did not wirk:
a[]='';
while ($p = mysqli_fetch_assoc($queryAns)) {
$countAnswers++;
a[] = $p['name'];
$arr .= $countAnswers.") "." ".$p['name']."\n";
}

The .= operator in PHP is used to concatenate strings. In order to append a new element to your array you need to do:
array_push($arr, $countAnswers.") "." ".$p['name']."\n");

Related

Foreach loop with Concatenation assignment

<?php
$names =array('Alex','Billy','Tabby');
$names_str=null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key!= (count($names)-1))
{
$names_str.=', ';
}
}
echo $names_str;
?>
why do we set names_str=null?
why do we put count($names-1)) how does this loop work?
<?php
$names = array('Alex','Billy','Tabby');
$names_str = null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key != (count($names) - 1))
{
$names_str .=', ';
}
}
echo $names_str;
?>
Why do we set $names_str = null?
It is being initialized outside of the loop. If this is a string to be returned, technically doing $names_str = ""; would work better if you want a default value to show and aren't doing some sort of empty/null check...
Why do we put count($names-1))?
This checks the key # e.g. (0,1,2) against the count/length of the array minus 1 (array starts at 0), to see if we are referencing the last key/value pair in the array, to determine if the string should show a comma between the current value and next value, or not. If it's the last value, we don't want to show a "," at the end of the string.
How does this loop work?
$names_str .= $name; concatenates the $name values to the initial string, with the if/key check placing commas between each value. See above about the count. So you end up with "Alex, Billy, Tabby" as the final value for $names_str.
A better way to do this is to use PHP's implode function:
$comma_separated = implode(",", $names);
This would give you the same comma separated list.

Compare string from input field with value in multidimension array

$klasseinput = strtoupper(trim($_POST["klasseliste"]));
$data = file('student.txt');
$data = array_filter($data);
foreach($data AS $row){
$student[] = explode(';', $row);
}
$antall = count($student);
for ($i = 0; $i < $antall; $i++){
if($klasseinput == $student[$i][3]){
print('<tr><td>'.$student[$i][0]."</td><td>".$student[$i][1]."</td><td>".$student[$i][2]."</td><td>".$student[$i][3]."</td></tr>");
}
}
/////////STUDENT.txt//////////
ph;petter;hanssen;IT1
gb;Geir;Bjarvin;IT2
mj;Marius;Johansen;IT3
/////////////////////////////
I am trying to compare an input form with an item in the multidimension array, but even tho the variable from the input field is exactly the same as the value in the array, it doesnt pass the if check.
$student[0][3] = IT1
$student[1][3] = IT2
$student[2][3] = IT3
If you have made sure there is no white space spoiling the comparison, then you might find a function like this useful to look at the strings on both sides of the comparison. You might find there are spurious characters causing trouble.
function hexdump($str)
{
for($i=0; $i<strlen($str);$i++)
{
echo "[$i] [".bin2hex($str[$i])."] [".$str[$i]."]<br />";
}
}
For instance, the string read from the file might contain CR LF characters. You could get rid of them using str_replace().
Thanks to Ravinder Reddy for the answer that was simple and worked for me:
" trim the value for \t\n if($klasseinput == trim($student[$i][3])){ "

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='';
};

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;

How to handle my data?

Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_array);
}
}

Categories