I have a string like this:
$string = '[miniTrack, boxTrack]'
I want to turn it into an array of variables like this:
$array = [$miniTrack, $boxTrack];
So that I can perform loops and iterations through the variable. And access the variables they are referencing.
I tried eval but I can't figure out how to convert it to a PHP Variable.
I KNOW THAT THIS IS NOT IDEAL, THE STRUCTURE OF THE DATABASE THIS IS PULLING FROM CAN'T BE ADJUSTED UNFORTUNATELY
Your question starts unusually, because you show an array containing a single string that is comma-separated, rather than an array of individual strings.
You could try something like the following:
$arr = [];
$string = ['miniTrack, boxtrack'];
//split the one string into an array, trimming spaces
$vars= array_map('trim', explode(',', $string[0]));
foreach($vars as $var) {
$arr[] = $var; //add the var to the array
}
print_r($arr);
Array
(
[0] => miniTrack
[1] => boxtrack
)
And if you need to create a variable for each item, you can create "variable variables":
foreach($vars as $var) {
$my_var = $$var; //variable variable
}
It should be as easy as the following:
preg_match_all('~(\w+)~','[miniTrack, boxTrack]', $matches);
foreach($matches[1] as $var)
{
print $$var;
}
You can convert your strings to array like this. It may be not ideal but you can use try this.
$string = '[miniTrack, boxTrack]';
$string = str_replace(array('[',']'),array('', '' ), $string);
$array = explode(',',$string);
Here you can iterate your array whatever you want.
Related
$booked_seat=array(1,2);
if(in_array($seat,$booked_seat)){
$booked="red"; $book_seat="data-book='1'";
} else {
$booked=""; $book_seat="";
}
I want to put PHP variable in array
$booked_seat=array($id);
Is this possible in any way define variable in array?
You can do like this using explode() & array_shift() in php :
$str = '1,2,3';
$arr = [explode(",", $str)];
echo "<pre>";
print_r(array_shift($arr));
If you want a string instead of an array of numbers, you can use the join method http://php.net/manual/en/function.join.php.
$str = join(',', array(1, 2, 3));
If you are wanting to create an array out of a string like '1,2,3' you could use the explode method http://php.net/manual/en/function.explode.php.
$arr = explode(",", "1,2,3");
This question already has answers here:
How do I create a comma-separated list from an array in PHP?
(11 answers)
Closed 2 years ago.
I'm trying to concatenate array keys (which are originally a class properties). So what I did is:
echo '<pre>'.print_r(array_keys(get_object_vars($addressPark)),TRUE).'</pre>';
Outputs:
Array
(
[0] => streetAddress_1
[1] => street_address_2
[2] => city_name
[3] => subdivision_name
[4] => country_name
)
This is how I get the AddressPark object's properties names.
$arr = array_keys(get_object_vars($addressPark));
$count = count($arr);
I want to access the object properties by index, that is why I used array_keys.
$props = str_repeat("{$arr[$count-$count]},",$count-2).$arr[$count-1];
echo $props;
The results is:
streetAddress_1,streetAddress_1,streetAddress_1,country_name
It repeats $arr[0] = 'streetAddress_1' which is normal because in every loop of the str_repeat the index of $arr is $count-$count = 0.
So what I exactly want str_repeat to do is for each loop it goes like: $count-($count-0),$count-($count-1) ... $count-($count-4). Without using any other loop to increment the value from (0 to 4).
So is there another way to do it?
No, you cannot use str_repeat function directly to copy each of the values out of an array into a string. However there are many ways to achieve this, with the most popular being the implode() and array_keys functions.
array_keys extracts the keys from the array. The following examples will solely concentrate on the other part of the issue which is to concatenate the values of the array.
Implode
implode: Join array elements with a string
string implode ( string $glue , array $pieces )
Example:
<?php
$myArray = ['one','two','three'];
echo implode(',', $myArray);
// one,two,three
echo implode(' Mississippi;', $myArray);
// one Mississippi; two Mississippi; three Mississippi;
Foreach
foreach: The foreach construct provides an easy way to iterate over arrays, objects or traversables.
foreach (array_expression as $key => $value)
...statement...
Example:
<?php
$myArray = ['one','two','three'];
$output = '';
foreach ($myArray as $val) {
$output .= $val . ',';
}
echo $output;
// one,two,three,
Notice that on this version we have an extra comma to deal with
<?php
echo rtrim($output, ',');
// one,two,three
List
list: Assign variables as if they were an array
array list ( mixed $var1 [, mixed $... ] )
Example:
<?php
$myArray = ['one','two','three'];
list($one, $two, $three) = $myArray;
echo "{$one}, {$two}, {$three}";
// one, two, three
Note that on this version you have to know how many values you want to deal with.
Array Reduce
array_reduce: Iteratively reduce the array to a single value using a callback function
mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )
Example:
<?php
$myArray = ['one', 'two', 'three'];
echo array_reduce($myArray, function ($carry, $item) {
return $carry .= $item . ', ';
}, '');
// one, two, three,
This method also causes an extra comma to appear.
While
while: while loops are the simplest type of loop in PHP.
while (expr)
...statement...
Example:
<?php
$myArray = ['one', 'two', 'three'];
$output = '';
while (!empty($myArray)) {
$output .= array_shift($myArray);
$output .= count($myArray) > 0 ? ', ' : '';
}
echo $output;
// one, two, three
Notice that we've handled the erroneous comma in the loop. This method is destructive as we alter the original array.
Sprintf and String Repeat
sprintf: My best attempt of actually using the str_repeat function:
<?php
$myArray = ['one','two','three'];
echo rtrim(sprintf(str_repeat('%s, ', count($myArray)), ...$myArray), ', ');
// one, two, three
Notice that this uses the splat operator ... to unpack the array as arguments for the sprintf function.
Obviously a lot of these examples are not the best or the fastest but it's good to think out of the box sometimes.
There's probably many more ways and I can actually think of more; using array iterators like array_walk, array_map, iterator_apply and call_user_func_array using a referenced variable.
If you can think of any more post a comment below :-)
I have an array with some keys and I want to get the array values according to the array keys where the keys are in a string.
Example:
$arr = array(
"COV" => "Comilla Victorians",
"RK" => "Rajshaji Kings"
);
$str = "COV-RK";
Now I want to show Comilla Victorians VS Rajshaji Kings.
I can do it using some custom looping, But I need some smart coding here and looks your attention. I think there are some ways to make it with array functions that I don't know.
You could do something like:
echo implode(' VS ', array_map(function($v) use ($arr) { return $arr[$v]; }, explode('-', $str)));
So explode the string, map the resulting array, returning the value of the matching key in $arr, then just implode it.
You could try this:-
<?php
$arr = array(
"COV" => "Comilla Victorians",
"RK" => "Rajshaji Kings"
);
$str = "COV-RK";
$values = explode("-", $str); // explode string to get keys actually
echo $arr[$values[0]] . " VS " . $arr[$values[1]]; // print desired output
I have a key value pair string that I would like to convert to a functional array. So that I can reference the values using their key. Right now I have this:
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$MyArray = array($Array);
This is not bringing back a functional key/value array. My key value pairs are in a variable string which means the => is part of the string and i think this is where my problem is. Any help would be appreciated. All i am trying to do is convert the string to a functional key/value pair where I can grab the values using the key. My data is in a string so please don't reply with the answer "take them out of the string." I am aware that this will work:
$MyArray = array('Type'=>'Honda', 'Color'=>'Red');
But my probem is that the the data is already in the form of a string. Thank you for any help.
There is no direct way to do this. As such, you'll need to write a custom function to build the keys and values for each element.
An example specification for the custom function:
Use explode() to split each element based on the comma.
Iterate over the result and:
explode() on =>
Remove unnecessary characters, i.e. single quotes
Store the first element as the key and the second element as the value
Return the array.
Note: if your strings contain delimiters this will be more challenging.
You do need to "take them out of the string", as you say. But you don't have to do it manually. The other answer uses explode; that's a fine method. I'll show you another - what I think is the easiest way is to use preg_match_all() (documentation), like this:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$array = array();
preg_match_all("/'(.+?)'=>'(.+?)'/", $string, $matches);
foreach ($matches[1] as $i => $key) {
$array[$key] = $matches[2][$i];
}
var_dump($array);
You need to parse the string and extract the data:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$elements = explode(",",$string);
$keyValuePairs = array();
foreach($elements as $element){
$keyValuePairs[] = explode("=>",$element);
}
var_dump($keyValuePairs);
Now you can create your on array using the $keyValuePairs array.
Here is an example of one way you can do it -
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$realArray = explode(',',$Array); // get the items that will be in the new array
$newArray = array();
foreach($realArray as $value) {
$arrayBit = explode('=>', $value); // split each item
$key = str_replace('\'', '', $arrayBit[0]); // clean up
$newValue = str_replace('\'', '', $arrayBit[1]); // clean up
$newArray[$key] = $newValue; // place the new item in the new array
}
print_r($newArray); // just to see the new array
echo $newArray['Type']; // calls out one element
This could be placed into a function that could be extended so each item gets cleaned up properly (instead of the brute force method shown here), but demonstrates the basics.
so I have this variable $_GET which receives the value such as
set=QnVzaW5lc3M=|RmluYW5jZQ==
The values are base64 enconded using base64_encode() and then separated by a delimiter '|'. I'm using implode function to generate the value of the set variable.
Now, the question is, how can I get the values from the set variable into an array and base64 decode them as well ?
Any suggestions are welcome.
I tried this :-
$test = array();
$test = explode('|', $_GET['set']);
var_dump($test);
This throws the value which is not usable.
But this made no difference.
$data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
$result = array_map(
'base64_decode',
explode('|', $data)
);
var_dump($result);
This should work using foreach:
// Set the test data.
$test_data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
// Explode the test data into an array.
$test_array = explode('|', $test_data);
// Roll through the test array & set final values.
$final_values = array();
foreach ($test_array as $test_value) {
$final_values[] = base64_decode($test_value);
}
// Dump the output for debugging.
echo '<pre>';
print_r($final_values);
echo '</pre>';
The output is this:
Array
(
[0] => Business
[1] => Finance
)