PHP how to add slashes into array - php

i have a problem i want to add slashes at the starting and the end of each string of my array.
This is an example of my actual array :
$patte = array();
$patte[0] = "httpd";
$patte[1] = "vsftpd";
$patte[2] = 'gohphp';
$patte[3] = 'abcdef';
i use this array for taking information into a DataBase so i can't place slashes now, or this is going to not working.
(mysql_query ... while mysql_fetch_array ...)
I need to rename these entry.
For this i use a second array, and with the command : "preg_replace" i can translate every strings like i want.
But preg_replace want me to add slashes in $patte
I want to obtain an array like this
$pattes = array();
$pattes[0] = "/httpd/";
$pattes[1] = "/vsftpd/";
$pattes[2] = '/gohphp/';
$pattes[3] = '/abcdef/';
Can you help me please.
I'm gonna have like 1000 line into this array.

Using array_map() you can apply callback to every element of your array :
function addSlashes($str)
{
return "/".$str."/";
}
$newArray = array_map("addSlashes", $patte);//array with the new values

Use array_map:
$pattes = array_map(function($str) {
return '/'.$str.'/';
}, $pattes);

Related

Make first item in array appear at the last item

Just to note I dont mean to reverse the whole array, just one item which is at the beginning of the array to also appear at the end of the array
I have an example of an array but i dont know how i can make mine to look the same.
I wanted to create a polygon using co-ordinate, and i found an example on the net that draws the polygon using an array. Below is the array that i found from the site
$polygon = array("-50 30","50 70","100 50","80 10","110 -10","110 -30","-20 -50","-30 -40","10 -10","-10 10","-30 -20","-50 30");
Condition is that the first and last array must be the same. And their example is from static numbers.
In my case i have dynamic list of coordinates from the database and i would wish it to generate something like the example given above.
Here is what i have tried but it does not seem to work. My code now
$query_points = mysqli_query($link,"SELECT * FROM ec");
$row_points = mysqli_fetch_assoc($query_points);
$query_lastpoint = mysqli_query($link,"SELECT * FROM ec"
$row_lastpoint = mysqli_fetch_assoc($query_lastpoint);
$longitude_last = $row_lastpoint['longitude'];
$latitude_last = $row_lastpoint['latitude'];
$polygon= array();
while ($row_points = mysqli_fetch_assoc($query_points))
{
$longitude_xx = $row_points['longitude'];
$latitude_yy = $row_points['latitude'];
$xx_yy = ''.$longitude_xx.' '.$latitude_yy.'';
$polygon[] = $xx_yy;
}
$polygon[] = "$longitude_last $latitude_last";
Its like from the source they use the variable directly as $polygon while mine is $polygon[]; and i cant say $polygon = $polygon[];
Any Assistance?
You can just append it again, if its already there it wont make a differnce
$array[]= $array[0];
otherwise you can do
if (end($array) != reset($array)) { //add the first element here
http://php.net/manual/en/function.end.php
http://php.net/manual/en/function.reset.php

How to Create the right array?

I'm using API Random.ORG with vendor engine LoLFactor\RandomORG\
My Code:
include '../vendor/autoload.php';
use LoLFactor\RandomORG\RandomORGClient;
$client = new RandomORGClient('5035-35353-53535-53535-3535');
$data = $client->generateSignedIntegers(1, 1, 60);
$i = 0;
$arr = array();
foreach($data as $randomInt) {
array_push($arr, ($randomInt));
}
echo '<br>';
var_dump(json_encode($arr));
And i get array
"["2.0",{"random":{"method":"generateSignedIntegers","hashedApiKey":"FZSXJR+2P+umSj1UIOvBEc3RpYuwh8ZQfqppk8O5froIsgTlcPWRmoYkKzLB07cCs4TXgMcZS+MduDyF0RK9+Q==","n":1,"min":1,"max":60,"replacement":true,"base":10,"data":[48],"completionTime":"2015-10-03 11:52:32Z","serialNumber":276},"signature":"B8FsTieibcDqHCa3uK2zTGC6ZCwx42ZyzIhymvg2RnPFYidcNwQ086ljhL8w+Ul6ui+y2OPlSymB4Zse+R6pmDlRNzgFvbhe+TqCyq8I41UU6lQyGIQq\/EGuyt+7qKAaEYOj1v98xsxQ1r7Ttxb1bJnWi7bNuVe5S0YiVo\/7JrP25RoLiso0K4P62mnySfFtCwR5j7MXM2OErQbxI6vVuvBh3bLS6jvuL7FWURs5RJZr0Ii2QZnK994PRtGz1kLjooVOII2t7cNejzq66Wc6ayLoasWgWaEXaKsQ9hTOeBCECWdA1woDy68QtEuZMr6cknhOdjmpNqiB+hYnkWitxecLVPTHW2UGG19OqwBfPQ0EHV+vnEyxoGlihf+xhjt+Pp56leKN69XKI0IxmgJAYcr99AJs0c4WUdl93Ft+mexCvOrf+7AVmMpqa6LCCJBaY2RRAL+mwSZO\/tVRaN3iiZRfAXXRqc\/nTKgHA3a+LnqOraxM\/wQidzzxyBsmSKbQIIDR0XFZbbGLlBStRFUeYRUonKLUlt5O9dn9Dm7OWiBH+Sg3gw7mBNNg9elyfMlgndSHHIk5xi1bSlNexZ3GHEljpB2VDsLI3WC1pOygdwobgZyIK4hrISPqhfolAWfI8B\/LRoaeZ5osNiGV79KaESy3VpDk4epLL\/7T0DaRErY=","bitsUsed":6,"bitsLeft":248458,"requestsLeft":742,"advisoryDelay":0},"G5nucL0Wdy9xtbejw"]"
Its bad browser console:
But i need array this type:
"{"random":{"method":"generateSignedIntegers","hashedApiKey":"FZSXJR+2P+umSj1UIOvBEc3RpYuwh8ZQfqppk8O5froIsgTlcPWRmoYkKzLB07cCs4TXgMcZS+MduDyF0RK9+Q==","n":1,"min":1,"max":60,"replacement":true,"base":10,"data":[48],"completionTime":"2015-10-03 11:52:32Z","serialNumber":276},"signature":"B8FsTieibcDqHCa3uK2zTGC6ZCwx42ZyzIhymvg2RnPFYidcNwQ086ljhL8w+Ul6ui+y2OPlSymB4Zse+R6pmDlRNzgFvbhe+TqCyq8I41UU6lQyGIQq\/EGuyt+7qKAaEYOj1v98xsxQ1r7Ttxb1bJnWi7bNuVe5S0YiVo\/7JrP25RoLiso0K4P62mnySfFtCwR5j7MXM2OErQbxI6vVuvBh3bLS6jvuL7FWURs5RJZr0Ii2QZnK994PRtGz1kLjooVOII2t7cNejzq66Wc6ayLoasWgWaEXaKsQ9hTOeBCECWdA1woDy68QtEuZMr6cknhOdjmpNqiB+hYnkWitxecLVPTHW2UGG19OqwBfPQ0EHV+vnEyxoGlihf+xhjt+Pp56leKN69XKI0IxmgJAYcr99AJs0c4WUdl93Ft+mexCvOrf+7AVmMpqa6LCCJBaY2RRAL+mwSZO\/tVRaN3iiZRfAXXRqc\/nTKgHA3a+LnqOraxM\/wQidzzxyBsmSKbQIIDR0XFZbbGLlBStRFUeYRUonKLUlt5O9dn9Dm7OWiBH+Sg3gw7mBNNg9elyfMlgndSHHIk5xi1bSlNexZ3GHEljpB2VDsLI3WC1pOygdwobgZyIK4hrISPqhfolAWfI8B\/LRoaeZ5osNiGV79KaESy3VpDk4epLL\/7T0DaRErY=","bitsUsed":6,"bitsLeft":248458,"requestsLeft":742,"advisoryDelay":0}"
Its good browser console:
without code ["2.0", and code ,"G5nucL0Wdy9xtbejw"] at end.
How i can delete first and last key-values. ?
I try array_merge , array_split but do not understand. How to create array that i need..
Sounds like instead of var_dump(json_encode($arr)); you just want var_dump(json_encode($arr[1])); ... as in, add the [1] to get the middle element of the array.
Alternatively, $arr = $arr[1];
But, array_slice, array_pop, array_shift won't really help you. They'll shorten the array to a single element, but you don't want the outer array at all, so just extract the middle element that you do want.

PHP - Extracting ids from a string to run against a function

I was wondering if someone could help me out.
Im extracting a string from my database which is formatted like so 4,3,1,7,38 etc etc ... its a dynamic array so it could be any number of numbers etc etc
What i need to do is extract each number and run it agains a function .. So for example each number represents a users id, i need to run each user id against a function and return a set result, so for each id i would neeed to run something like
$personsdetails = $this->random_model->get_user_details( $useridhere );
How would i go about getting each of the ids out of the array and running it over a loop to get each persons details?
Cheers
You can use explode and foreach over created array.
$userIds = explode(',', $yourstring);
foreach ($userIds as $userId) {
$personsdetails = $this->random_model->get_user_details( $userId );
}
$ids_raw = '1,2,3,4,5';
$ids = explode(',', $ids_raw);
foreach($ids as $id){
echo $id;
}
$var=explode(',',$database_value);
its comming in array
Because you're bringing in a single dimension array, I'd suggest using a for() loop (personal preference). The explode() function will split
a string by the first argument you give it. So in this case, explode is splitting the string in $userIDs by commas ','. Then we run each array element through your function.
$userIDs = '1,2,3';
$userIDs = explode(',',$userIDs);
for($x=0;$x<count($userIDs);$x++){
$personsdetails = $this->random_model->get_user_details($userIDs[$x]);
};

While script inside of an array

pretty straight forward question this - I am trying to create an array to store the Model and Cost values taken from my database table. I figured I could begin the array, then create a while loop, and then end the array, and smiles all around. I may be mistaken, or I may have blindly missed something in my code, but could you have a look?
$array = array(
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$overall_cost["model"] => $overall_cost["cost"],
}
);
var_dump($array);
I think this is what you're looking for:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);
You can't do it like this. You need to add to the array inside the while loop:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);
would be one way of doing it.
EDITED to produce simple array.
I don't think that will work. Try something like:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);

Sending array as one variable from JavaScript to PHP

I have a form, and the URL is like this:
http://hostname/projectname/classname/methodname/variablename
And in my JavaScript, I fill an array like this:
var currentrelations = new Array();
$(".ioAddRelation").each(function(index) {
currentrelations[index] = $(this).html();
});
And this array has two values ['eeeeee','eeeeee']
So the url is:
http://localhost/Mar7ba/InformationObject/addIO/eeeeee,eeeeee
And in my PHP, in the class InformationObject, on the method addIO:
public function addIO($currentRelations =null) {
$name = $_POST['name'];
$type = $_POST['type'];
$concept = $_POST['concept'];
$contents = $_POST['contents'];
$this->model->addIO($name, $type, $concept, $contents);
if (isset($_POST['otherIOs'])) {
$otherIOs = $_POST['otherIOs'];
$this->model->addOtherIOs($name, $otherIOs);
}
$NumArguments = func_num_args();
if ($currentRelations!=null) {
$IOs = $_POST['concetedIOs'];
$this->model->setIoRelations($name,$IOs, $currentRelations);
}
exit;
include_once 'Successful.php';
$s = new Successful();
$s->index("you add the io good");
}
But when I print the array $currentRelations using this statement:
echo count($currentRelations)
The results was 1 not 2, and when I print the first element using thie statement echo $currentRelations[0] I get e not eeeeee
why is that? What is the solution? What am I doing wrong?
As I commented, the $currentRalations is a string, so using count on any type which is not an array or an object will return 1.
Also, note that when you do this $currentRelations[0] on a string, you are accessing a character in the zero-based index of the string. As strings are arrays of characters you can use the square array brackets to access specific chars within strings. This is why echo $currentRelations[0]; printed e in your code.
To split a string you should use the explode function like this:
$curRel = explode(',', $currentRelations);
and then see what you get
var_dump($curRel);
Hope it helps.

Categories