Array by expressions - php

In php I have the following variable which comes from a url:
$data = "data_id=value1/config/value2/config/value3";
It always comes in the following format:
data_id = first value of the parameter to come
/ config / -> which is a kind of parameters tab
second parameter + / config / + etc ...
I want these values ​​to be inserted into an array, i.e., what would happen is the following:
The Wrath php gets the variable $data, would catch the first parameter, in this case e.g. value1 (which'll come after the data_id) and insert it into the array as a vector 1, soon after it takes the / config / and recognizes that it is a separator, thus making it take the value 2 and enter the array, making this loop until the end.
example:
$data = "data_id =fish/config/horse/config/car";
The array will look as follows:
array
{
[0] -> fish
[1] -> horse
[2] -> Car
}
could someone help me?

Assuming data_id is a GET variable, you can do something like this.
$data = $_GET['data_id']
$myArray = explode('/config/', $data);
explode() documentation

<?php
$data = 'data_id=value1/config/value2/config/value3';
list($name, $value) = explode('=', $data, 2);
$result = explode('/config/', $value);
print_r($result);
Example

If the entire thing is a string you can use strpos to get the position of the = character and cut it away using substr. Then simply explode the entire thing with php explode.
$data = "data_id =fish/config/horse/config/car";
$data = explode( "/config/", substr( $data, strpos( $data, '=' )+1 ) );
Will result in:
array(3) {
[0]=>
string(4) "fish"
[1]=>
string(5) "horse"
[2]=>
string(3) "car"
}
strpos()
substr()
explode()

Related

How to Remove Elements from array in php after some given character?

I want to Remove all the Elements from my array which is after , but I am unable to do this.
I have an array like this => ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"]
and I want to print array something like this => ["18-08-2022","18-08-2022"]
I want to remove Elements after the ,
This is what I tried
<?php
while ($row = mysqli_fetch_array($result)) {
$Etime[] = $row["Etime"];
$Etime1[]=$row["Etime"];
$E2[]=substr($Etime1[],',',true);
}
$Etime = json_encode($Etime);
$Etime1=json_encode($Etime1);
echo $Etime1
?>
this is easy-
steps to do so-
1.Parse your array as string.
2.store that in a variable.
3. then use a if loop and use php explode funtion. explode function will seperate that string elements by the seperator in this case the "," you want to remove.
explode(string $separator, string $string)
where,
separator-The boundary string.
string-The input string.
limit
example=
$text = "hello,there";
//using explode-
var_dump( explode( ',', $input2 ) );
output=
array(2)
(
[0] => string(5) "hello"
[1] => string(5) "there"
)
more about explode() here- https://www.php.net/manual/en/function.explode.php
Here's a simple php that generates the output you want. Since you only need date bits I have provided you with only the date bits. You can get general idea from here
$arr = ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"];
//
// sample output: [ "18-08-2022", "18-08-2022" ]
//
$dateMappedToYourFormat = array_map(function($dt) {
return explode(",", $dt)[0]; // getting everything before comma
}, $arr);
echo implode(",", $dateMappedToYourFormat); //to view your result

Remove characters from Array values

Thanks guys.
I've been towing over this one for over a day now and it's just too difficult for me! I'm trying to remove the last 3 characters from each value within an array. Currently, I've tried converting to a string, then doing the action, then moving into a new array... can't get anything to work. Someone suggested this, but it doesn't work. I need an array of postcodes, "EC1 2AY, EC3 4XW..." converting to "EC1, EC3, ..." and it be back in an Array!!
implode(" ",array_map(function($v){ return ucwords(substr($v, 0, -3)); },
array_keys($area_elements)));
This hasn't worked, and obviously when I converted to a string and do a trim function, it will only take the last 3 characters from the last "variable" in the string.
Please send HELP!
If you want an array back, you shouldn't implode. You are almost there:
$area_elements = ['EC1 2AY', 'EC3 4XW'];
$result = array_map(function($v){
return trim(substr($v, 0, -3));
}, $area_elements);
var_dump($result);
Output:
array(2) {
[0]=>
string(3) "EC1"
[1]=>
string(3) "EC3"
}
Another solution:
altering array by reference.
Snippet
$area_elements = ['EC1 2AY', 'EC3 4XW'];
foreach($area_elements as &$v){
$v = substr($v, 0, -4);
}
print_r($area_elements);
Output
Array
(
[0] => EC1
[1] => EC3
)
Live demo
Pass by reference docs

PHP string with int or float to number

If I have two strings in an array:
$x = array("int(100)", "float(2.1)");
is there a simple way of reading each value as the number stored inside as a number?
The reason is I am looking at a function (not mine) that sometimes receives an int and sometimes a float. I cannot control the data it receives.
function convertAlpha($AlphaValue) {
return((127/100)*(100-$AlphaValue));
}
It causes an error in php
PHP Notice: A non well formed numeric value encountered
which I want to get rid of.
I could strip the string down and see what it is and do an intval/floatval but wondered if there was a neat way.
UPDATE:
Playing about a bit I have this:
function convertAlpha($AlphaValue)
{
$x = explode("(", $AlphaValue);
$y = explode(")", $x[1]);
if ($x[0] == "int") {
$z = intval($y[0]);
}
if ($x[0] == "float") {
$z = floatval($y[0]);
}
return((127/100)*(100-$z)); }
This which works but it just messy.
<?php
$x = array("int(100)", "float(2.1)");
$result = [];
foreach($x as $each_value){
$matches = [];
if(preg_match('/^([a-z]+)(\((\d+(\.\d+)?)\))$/',$each_value,$matches)){
switch($matches[1]){
case "int": $result[] = intval($matches[3]); break;
case "float": $result[] = floatval($matches[3]);
}
}
}
print_r($result);
OUTPUT
Array
(
[0] => 100
[1] => 2.1
)
The simplest would simply be to make the array as you need it, so instead of
$x = array("int(100)", "float(2.1)");
you have:
$x = [100, 2.1];
but as this is not what you want you got two choices now. One, is to use eval(), for example:
$x = ['(int)100', '(float)2.1'];
foreach ($x as $v) {
var_dump(eval("return ${v};"));
}
which will produce:
int(100)
double(2.1)
As you noticed, source array is bit different because as there is no such function in PHP as int() or float(), so if you decide to use eval() you need to change the string to be valid PHP code with the casting as shown in above example, or with use of existing intval() or floatval() functions. Finally, you can parse strings yourself (most likely with preg_match()), check for your own syntax and either convert to PHP to eval() it or just process it in your own code, which usually is recommended over using eval().
The way I would do it is by using a regex to determine the type and value by 2 seperate groups:
([a-z]+)\((\d*\.?\d*)\)
The regex captures the alphanumeric characters up and until the first (. It then looks for the characters between the ( and ) with this part: \d*\.?\d*.
The digit-part of the regex accepts input like: 12.34, .12, 12. and 123
$re = '/([a-z]+)\((\d*\.?\d*)\)/m';
$input_values = array('int(100)', 'float(2.1)');
foreach($input_values as $input) {
preg_match_all($re, $input, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
}
Which leads to the output below. As you can see, there is the type in the [1] slot and the number in the [2] slot of the array
array(1) {
[0]=>
array(3) {
[0]=>
string(8) "int(100)"
[1]=>
string(3) "int"
[2]=>
string(3) "100"
}
}
array(1) {
[0]=>
array(3) {
[0]=>
string(10) "float(2.1)"
[1]=>
string(5) "float"
[2]=>
string(3) "2.1"
}
}
You can then use a check to perform the casting like:
$value;
if(matches[1] === "int") {
$value = intval($matches[2]);
} elseif (matches[1] === "float") {
$value = floatval($matches[2]);
}
The latter code still needs error handling, but you get the idea. Hope this helps!
PHP is historically typed against strings so it's pretty strong with cases like these.
$x = array("int(100)", "float(2.1)");
^^^ ^^^
You can actually turn each of those strings into a number by multiplying the substring starting after the first "(" with just one to turn it into a number - be it integer or float:
$numbers = array_map(function($string) {
return 1 * substr(strstr($string, '('), 1);
}, $x);
var_dump($numbers);
array(2) {
[0] =>
int(100)
[1] =>
double(2.1)
}
That is PHP takes everthing numberish from a string until that string seems to end and will calculate it into either an integer or float (var_dump() shows float as double). It's just consuming all number parts from the beginning of the string.
Not saying existing answers are wrong per-se, but if you ask that as a PHP question, PHP has a parser very well for that. My suggestion is to just remove the superfluous information from the beginning of the string and let PHP do the rest.
If you want it more precise, regular expressions are most likely your friend as in the yet top rated answer, still combined with PHP will give you full checks on each string:
$numbers = array_map(function($string) {
$result = preg_match('~^(?:int|float)\(([^)]+)\)$~', $string, $group) ? $group[1] : null;
return null === $result ? $result : 1 * $result;
}, $x);
So all non int and float strings will be turned into NULLs (if any).

Delimited Filename Parsed into Table Row Data

I am attempting to convert variable width, pipe (|) delimited file names into table data.
E.g.
var1|var2|var3|var4|var5.pdf
becomes
<table border="2" bordercolor="#ffffff" width="100%" cellpadding="10" cellspacing="10">
<tr>
<td>$var1</td>
<td>$var2</td>
<td>$var3</td>
<td>$var4</td>
<td>$var5</td>
</tr>
</table>
I have everything up to, and after var1 but cannot figure out how to parse the remaining variables out.
This is where I have tossed the towel and decided to post here:
$var1 = substr($file_name, 0, strpos($file_name, '|'));
Ideas?
Thank you in advance!
Maybe you can put all the fields in an array using explode(), like this:
PHP
<?php
$data = "var1|var2|var3|var4|var5.pdf";
$fields = explode("|", $data);
var_dump($fields);
?>
OUTPUT
array(5) { [0]=> string(4) "var1" [1]=> string(4) "var2" [2]=> string(4) "var3" [3]=> string(4) "var4" [4]=> string(8) "var5.pdf" }
You can use list() in conjuction with explode() if you want each value in its separate variable, like this:
list($var1,$var2,$var3,$var4,$var5) = explode('|', $filename);
I suggest that you explode the filenames into an array rather than creating variables for each one, but I have given example code on how to achieve this anyway. I hope I answered your question correctly.
<?php
$string = 'var1|var2|var3|var4|var5.pdf';
// Trim the string of dangling pipes to make sure we don't get empty array elements.
$string = trim($string, '|');
// Split the filenames into an array. Much more managable that way.
$filenames = explode('|', $string);
// Define an empty array to put our variables in.
$variables = array();
// Because the array we made is not associative we can iterate through with a for loop.
for($i = 0; $i < count($filenames); $i++) {
// Make our variable names start from one; much more human-friendly. Add them to an array to extract later.
$var_name = 'var' . ($i + 1);
$variables[$var_name] = $filenames[$i];
}
// Extract the values of the array and place them into variables named after the array keys.
extract($variables, EXTR_OVERWRITE);
This will create the following variables (along with their values).
$var1 = 'var1';
$var2 = 'var2';
$var3 = 'var3';
$var4 = 'var4';
$var5 = 'var5.pdf';
You're looking for the explode() function.
$parts_arr = explode('|', $filename);
var_dump($parts_arr);
Also, pipes are special characters in just about every shell I can think of, I strongly recommend not using them in a file name.

Creating a dynamic PHP array

I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);

Categories