PHP From string to two variables - php

In my db there is a table that have some values like this[string]
100/100
50/100
40/80
7/70
I need to change this values in
100%
50%
50%
10%
How can i do this using only PHP/mysql code?
EDIT:this is the code:
foreach ($html->find('div.stat') as $status_raw){
$status = $tag_pic_raw->src;
$status = mysql_real_escape_string($status);
$data->query("INSERT IGNORE INTO `tb` (`value`) VALUES ('".$status."')");
}
I have used a DOM inspector to get info from another site

Used explode() combined with some math.
$str = '40/80';
$vals = explode('/', $str);
$percent = (($vals[0] / $vals[1]) * 100).'%';
echo $percent;

use explode() to divide up the values and then math them.
foreach($array as $val) // assuming all the (##/##) values are in an array
{
$mathProblem = explode("/", $val);
echo (intval($mathProblem[0]) / intval($mathProblem[1]) * 100)."%<br />";
}

You can set up a function similar to this:
function math($one)
{
$new = explode("/", $one);
$math = $new[0] / $new[1];
$answer = $math * 100;
return $answer."%";
}
Then every time you need to query something, you can do it simply by doing this:
foreach ($results as $r)
{
echo math($r);
}
This just makes it (I think) tidier and easier to read.

Use explode() :Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter( / in this case).
$arr=array('80/100','50/100','40/80');
foreach($arr as $str){
$values = explode('/',$str);
echo ((int)$values[0]/(int)$values[1])*100.'%<br/>';
}

Related

Replacing ',' characters in only odd positions

I need replace ',' characters with regex in php, but only in odd positions
I have:
{"phone","11975365654","name","John Doe","cpf","42076792864"}
I want replace ',' to ':', but only the odd:
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}
I'm trying this regex:
preg_replace('/,/', ':', $data)
But it get all quotes and no only the odd.
Can you help me?
Make it simple:
preg_replace('/(("[a-z]+"),(".+?"))+/', '$2:$3', $a)
Rather than regex, this just converts the list to an array (using str_getcsv() to cope with the quotes). Then loops every other item in the list, using that item as the key and the next item as the value. This can then be json_encoded() to give the result...
$data = str_getcsv(trim($input, "{}"));
$output = [];
for ( $i=0, $k=count($data); $i < $k; $i+=2) {
$output[$data[$i]] = $data[$i+1];
}
echo json_encode($output);
It is not ideal to use regex for this task. Having said that, if you know that your input can be matched by a simple regex, this should do it :
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$result = preg_replace('/,(.*?(?:,|[^,]*$))/ms', ':\\1', $str);
This lenient to some extra characters but it will fail if any string contains commas
Example
Here's an example of using standard PHP functions:
$input = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$dataIn = str_getcsv(trim($input, '{}'));
$keys = array_filter($dataIn, function ($key) { return !($key & 1); }, ARRAY_FILTER_USE_KEY);
$values = array_filter($dataIn, function ($key) { return $key & 1; }, ARRAY_FILTER_USE_KEY);
$DataOut = array_combine($keys, $values);
$output = json_encode($DataOut);
echo $output;
This code is a lot longer than using a regex, but it is probably easier to read and maintain in the long run. It can cope with commas in the values.
Another option could be using array_splice and loop while there are still elements in the array:
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$data = str_getcsv(trim($str, '{}'));
$result = array();
while(count($data)) {
list($k, $v) = array_splice($data, 0, 2);
$result[$k] = $v;
}
echo json_encode($result);
Output
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}

How to truncate a delimited string in PHP?

I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.
Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);
Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....
I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}
Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;

PHP Break Apart Array Variables

I am extracting XML from a feed. There is a tag entitled:
<georss:point>34.234 -34.435</georss:point>
which contains two variables I am inserting into MySQL
When I run this code, the variable is 'array'. I then place an extract to break out the variables, unsure of next
$xmlString = str_replace('georss:point','point',$xmlString);
$xml = new SimpleXMLElement($xmlString);
$items = $xml->xpath('channel/item');
$closeItems = array();
foreach($items as $item)
{
$latlng = explode(' ',trim($item->point));
array(
'lat'=>$latlng[0],
'lng'=>$latlng[1]
);
$lat = array($latlng[0]);
$lng = array($latlng[1]);
echo $lat;
echo $lng;
}
When I place those echo statements (in the last two lines of code), the variables get echod to the screen. However when I place these varaibles outside of the array, the values do not get echod.
I am attempting to get these variables outside of the array, so that I can insert these variables into the database. I have tried extract on the varaiables, but this prints back to the screen as 'Array'... unsure of what I need to do to extract these variables from the array. Thanks,
Replace your foreach with a version like this...
$new_array = array();
foreach($items as $item)
{
$latlng = explode(' ',trim($item->point));
$new_array[] = array('lat'=>$latlng[0],'lng'=>$latlng[1]);
}
var_dump($new_array);
this should give you a array of your lat/long values.
Some observations.
1) you can register xpath namespaces instead of replacing in the string
2) array('lat'=>$latlng[0],'lng'=>$latlng[1]); does nothing. It is a dead store.
3) Instead of
$lat = array($latlng[0]);
$lng = array($latlng[1]);
echo $lat;
echo $lng;
You can do: echo $latlng[0].'-'.$latlng[1];
If you try to echo an array, you will always get Array.
Use a specific index to echo an individual element.
4) Alternatively you could use list to store the variables directly
list($lat, $long) = explode(' ',trim($item->point));
Edit
To insert multiple results into your database, store the results in an array:
$lat_long = array();
foreach($items as $item){
$lat_long[] = explode(' ', $item);
}
Then later iterate through this array and do your database insert.
foreach($lat_long as $point){
//do SQL injection prevention as well
//INSERT INTO your_table (`lat`, `long`) VALUES ($point[0], $point[1]);
}
I think this:
$lat = array($latlng[0]);
$lng = array($latlng[1]);
should be:
$lat = $latlng[0];
$lng = $latlng[1];
Obmitting the array(..) around $latlng[..] would do the trick, I think.
$lat = $latlng[0];
$lng = $latlng[1];

PHP - actually execute value of variable

I have an array of fractions:
$fractions = array('1/8', '1/4', '1/2');
Is there any way that I can get PHP to actually perform the division to get a decimal value?
Something like:
foreach($fractions as $value) {
$decimal = [the result of 1 divided by 8, or whatever the current fraction is in value];
}
The way you have it, you should just explode and do your division:
foreach($fractions as $value) {
$exp = explode('/',$value);
$decimal = $exp[0] / $exp[1];
}
You could also eval(), but I usually try not to do that. It is a performance hit as well.
You can call eval():
$fractions = array('1/8', '1/4', '1/2');
foreach($fractions as $value) {
$decimal = eval("return $value;");
echo "$value = $decimal\n";
}

PHP for loop will affect the page load speed?

$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);
for($x=0;$x<count($categs);$x++){
for($y=0;$y<count($categories);$y++){
if($categs[$x] == $categories[$y]){
$str .= $y.",";
}
}
}
echo str; // 0,3,1,
Will this code will affect page render time? Can I do it using any other fast methods?
Thanks in advance.
$str = implode(',', array_keys(array_intersect($categories, $categs)));
You can use array_intersect() to find the common items and then use implode() to construct a comma-separated list:
Str = implode(',', array_intersect($categories, $categs)) . ',';
Unless you're dealing with a large number of items (thousands) it won't affect page speed. The one issue is that this intersection is O(n2). Putting the values into keys could speed it up considerably as that changes lookup time from O(n) to near O(1) making the whole operation O(n).
yes it will since you are looping in a loop.
Best thing is to check with in array:
$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);
$str = array();
foreach($categs as $id => $categs_check)
{
if(in_array($categs_check, $categories))
{
//its better to put it into a array and explode it on a later point if you need it with comma.
$str[] = $id;
}
}
I'm not completely sure what you are trying to do but it should be something like the above
I don't think that str_replace is a faster method than all the array functions but another possible solution is:
$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
foreach($categories as $i=> $c) {
$sql = str_replace($c, $i, $sql);
}
$arrCategories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$arrCategs = explode(",",$sql);
$arrAns = array();
for($i = 0, $intCnt = count($arrCategs); $i <= $intCnt; $i++) {
if(in_array($arrCategs[$i],$arrCategories)) {
$arrAns[$arrCategs[$i]] = array_search($arrCategs[$i], $arrCategories);
}
}
print "<pre>";
print_r($arrAns);
print "</pre>";

Categories