php - different variables with string, one array - php

Here are my variables:
$a = Hello Mister
$b = I play basketball
$c = You walk in the city
$d = My name is Mary
$e = Where is Bryan
I tried of course the explode " ", but it does not work because each variable has words with spaces.
I also tried to adapt the chunk_split and the str_split, without success.
(...)

You can simply add variables in array separated by comma, see example below:
$arr = array($a, $b, $c);
Or you can also append newly found variable as below :
$arr[] = $d;

The solution is:
Keep the variable names in an array, like this:
$varArray = array('a', 'b', 'c', 'd', 'e');
Create an empty result array, like this:
$resultArray = array();
Loop through this variable array $varArray using foreach loop. In each iteration use variable variables to get the string and append it to the result array $resultArray, like this:
foreach($varArray as $v){
$resultArray[] = $$v;
}
Here's the complete code:
$a = 'Hello Mister';
$b = 'I play basketball';
$c = 'You walk in the city';
$d = 'My name is Mary';
$e = 'Where is Bryan';
$varArray = array('a', 'b', 'c', 'd', 'e');
$resultArray = array();
foreach($varArray as $v){
$resultArray[] = $$v;
}
// display $resultArray
var_dump($resultArray);

You can do that very simply.
$a = "Hello Mister";
$b = "I play basketball";
$c = "You walk in the city";
$d = "My name is Mary";
$e = "Where is Bryan";
$sentence = array($a,$b,$c,$d,$e);
// or index can be assigned manually
$sentence[0] = $a;
$sentence[1] = $b;
$sentence[2] = $c;
$sentence[3] = $d;
// you can add new variable like below. And indexing automatically maintain sequence by itself.
$sentence[] = $e;
echo "<pre>";
print_r($sentence);
echo "</pre>";
// output
Array
(
[0] => Hello Mister
[1] => I play basketball
[2] => You walk in the city
[3] => My name is Mary
[4] => Where is Bryan
)
If you have any further query regarding this you can ask fell free. Thanks

Related

Get the name of the variable which has the second lowest/smallest value with PHP

I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the second smallest value?
Thanks.
Use compact to set the variables to one array, sort the array, then use array slice to get the second value.
Then optionally echo the key of the second value.
$a = 2;
$b = 7;
$c = 6;
$d = 1;
$arr = compact('a', 'b', 'c', 'd');
asort($arr);
$second = array_slice($arr,1,1);
Echo "variable name " . Key($second) ."\n";
Echo "value " . ${key($second)};
https://3v4l.org/SVdCq
Updated the code with how to access the original variable from the array
Unless you have a structured way of naming your variables eg prefix_x there is no real way.
Recommended way is using an array like this:
$array = array(
"a" => 3,
"b" => 2,
"c" => 1,
"d" => 6
);
// Sort the array descending but keep the keys.
// http://php.net/manual/en/function.asort.php.
asort($array);
// Fetch the keys and get the second item (index 1).
// This is the key you are looking for per your question.
$second_key = array_keys($array)[1];
// Dumping the result to show it's the second lowest value.
var_dump($array[$second_key]); // int(2).
To be more in line with your question you can create your array like this.
$array = array();
$array['variable_one'] = $variable_one;
$array['some_random_var'] = $some_random_var;
$array['foo'] = $foo;
$array['bar']= $bar;
// Same code as above here.
Instead of using 4 variables for 4 integer values, you can use an array to store these values. Sort the array and print the second index of the array i.e. 1.
<?php
$x = array(2,3,1,6);
$i = 0, $j = 0, $temp = 0;
for($i = 0; $i < 4; $i++){
for($j=0; $j < 4 - $i; j++){
if($x[$j] > $x[$j+1]){
$temp = $x[$j];
$x[$j] = $x[$j+1];
$x[$j+1] = $temp;
}
}
}
for($j = 0; $j < 4; $j++){
echo $x[$j];
}
echo $x[1];
?>
First you need to have all Variables in an Array. You can do this this way:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
or this way:
$array['a'] = 3;
$array['b'] = 6;
// etc
Then you need to sort the Items with natsort() to receive a natural Sorting.
natsort($array);
Then you flip the Array-Keys with the Values (In Case you want the Value, skip this Line)
$array = array_flip($array);
After this you jump to the next Item in the Array (Position 1) by using next();
echo next($array);
Makes in Total a pretty short Script:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
natsort($array);
$array = array_flip($array);
echo next($array);

Each value of a string to a separate array conversion

I have a html page contents, that I converted into a string separated by "#".
Example:
(2R)-2-hydroxy#250.181#C15H24NO2#2#1#46#1#11#1.1266#1#18#6
Is there any way to convert each value of these string to convert into a array?
I need an output like this:
$a = (2R)-2-hydroxy
$b = 250.181
$c = C15H24NO2
$d = 2
$e = 1
//etc...
This should work for you:
Just explode() your string and loop through the array. Then you can assign each value to a variable, where you can increment the character.
$str = "(2R)-2-hydroxy#250.181#C15H24NO2#2#1#46#1#11#1.1266#1#18#6";
$arr = explode("#", $str);
$start = "a";
foreach($arr as $v) {
$$start = $v;
$start++;
}
This should work
$array = explode("#", "(2R)-2-hydroxy#250.181#C15H24NO2#2#1#46#1#11#1.1266#1#18#6");
$array [0] = (2R)-2-hydroxy
$array [1] = 250.181
...

PHP: Set value of nested array using variable as key

Lets say i have this kind of code:
$array = [
'a'=> [
'b' => [
'c'=>'some value',
],
],
];
$array['a']['b']['c'] = 'new value';
Of course this is working, but what i want is to update this 'c' key using variable, something like that:
$keys = '[a][b][c]';
$array{$keys} = 'new value';
But keys are treatening as string and this is what i get:
$array['[a][b][c]'] = 'new value';
So i would like some help, to show me the right way to make this work without using eval().
By the way, there can be any number of array nests, so something like this is not a good answer:
$key1 = 'a';
$key2 = 'b';
$key3 = 'c';
$array[$key1][$key2][$key3] = 'new value';
It isn't the best way to define your keys, but:
$array = [];
$keys = '[a][b][c]';
$value = 'HELLO WORLD';
$keys = explode('][', trim($keys, '[]'));
$reference = &$array;
foreach ($keys as $key) {
if (!array_key_exists($key, $reference)) {
$reference[$key] = [];
}
$reference = &$reference[$key];
}
$reference = $value;
unset($reference);
var_dump($array);
If you have to define a sequence of keys in a string like this, then it's simpler just to use a simple separator that can be exploded rather than needing to trim as well to build an array of individual keys, so something simpler like a.b.c would be easier to work with than [a][b][c]
Demo
Easiest way to do this would be using set method from this library:
Arr::set($array, 'a.b.c', 'new_value');
alternatively if you have keys as array you can use this form:
Arr::set($array, ['a', 'b', 'c'], 'new_value');
Hi bro you can do it like this throught an array of keys :
This is your array structured :
$array = array(
'a'=> array(
'b' => array(
'c'=>'some value',
),
),
);
This is the PHP code to get value from your array with dynamic keys :
$result = $array; //Init an result array by the content of $array
$keys = array('a','b','c'); //Make an array of keys
//For loop to get result by keys
for($i=0;$i<count($keys);$i++){
$result = $result[$keys[$i]];
}
echo $result; // $result = 'new value'
I hope that the answer help you, Find here the PHPFiddle of your working code.

How to assign variable dynamically to php list function

What I am doing that I want to generate a list based on how many items are in an array, so I have counted the items and loop over them, create a number based var and construct a string $var which contains $a1,$a2.... and assigns the $var to list list($var)
and tried to access $a1 but it gives me the error "Undefined variable: a1"
Is there any other way to do it?
Here is my code:
$arr = array('1','2','3');
$listsize = count($arr);
$var='';
for($i=1;$i<=$listsize;$i++){
$var.='$a'.$i;
if($i!=$listsize){
$var.=',';
}
}
list($var) = $arr;
echo $a1;
What you are looking for is variable variables.
In PHP, you can dynamically assign variables names (not just values).
Here is an example:
$foo = "Hello" . 1;
# In this line, I am taking the value of the variable $foo (Hello1) and
# using that as as a variable name. This is equivalent to
# $Hello1 = "World", except the variable is dynamic (hence variable variables).
$$foo = "World";
print $Hello1; # This will print World
Why not use extract()?
Try this:
$values = array('1','2','3');
$variables = array();
$length = count($values);
$key = 'a1';
for ($i = 0; $i < $length; $i++){
$variables[$key] = $values[$i];
$key++;
}
extract($variables);
echo $a1, $a2, $a3;
You can solve your problem without loops. Array $as is filled with your data, that has keys a1 to aX:
$arr = array('1', '2', '3', 'test', true, 4.56);
$keys = array_map(function($n) { return "a$n"; }, range(1, count($arr)) );
$a = array_combine($keys, $arr);
Array $as has keys and values like output bellow:
Array
(
[a1] => 1
[a2] => 2
[a3] => 3
[a4] => test
[a5] => 1
[a6] => 4.56
)
I advice you to use access to variables via array like $a['a3'], and not via variables like $a3.
If you would like to have $a1 ... $aX variables, extract array like:
extract($a);

Cleanest way of working out next variable name based on sequential order?

Hope my title explains it ok! Here's more detail:
I'm creating an array which stores keys & their values. Eg.
test1 = hello
test2 = world
test3 = foo
What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.
In the example below I want the next key to be 'test46', as it is the next highest value:
test6 = blah
test45 = boo
test23 = far
This sounds like you should be using an array with numerical indexes instead.
You could however use some code like this...
$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
$number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad.
Implementation of #alex answer without using a loop:
$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad
This data structure would be better stored as an array.
$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';
You then don't need to know the highest number to add a new item, just use the empty brackets syntax (shown above) to add an item to the end of the array.
You then have access to a wealth of array functions that PHP gives you to work with your data: http://php.net/manual/en/ref.array.php
When you want to get item 43 from the array, use:
echo $test[42];
Arrays are counted from 0 rather than 1, so item 43 will have an index of 42.
What are you using that for? If numbering the array is a must-have, just use a simple numerical indexed array instead, and simply prepend the key with "test" if you need it to show up as "test1":
<?php
$array = array(
6 => 'blah',
45 => 'boo',
23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "\n"; // this is 'new'
foreach( $array as $key => $value ) {
echo "test$key = $value<br />\n"; // test6 = blah
}

Categories