Trying to create a variable with unique name for each $item.
To prevent error "Only variables can be passed by reference".
If there are 5 items in array $items, we should get 5 unique variables:
$item_name_1;
$item_name_2;
$item_name_3;
$item_name_4;
$item_name_5;
All of them should be empty.
What is a true solution for this?
You can dynamically create variable names doing the following:
$item_name_{$count} = $whatever;
I must warn you though, this is absolutely bad style and I've never seen a good reason to use this. In almost every use case an array would be the better solution.
Well, I guess that you can use $item_name_{$count} = "lorem ipsum"; for it
... But won't be better to use an array?
I'm not sure I understand what you want to do, so this may be completely wrong. Anyway, if what you want is an array with empty values you can use this code:
<?php
$arr = array_fill(0, 3, '');
var_export($arr) // array ( 0 => '', 1 => '', 2 => '', 3 => '', )
?>
See array_fill for more information.
If this is the wrong answer, please clarify what you mean. I may be able to help you.
Related
There exists such:
$var1 = $var2 = "blabla";
but is there a way to set similar inside array? like:
array(
'key1'='key2' => "blabla",
...................
)
p.s. I dont need outside of array functions, like array_fill_keys or etc.. I want inside-array solution (if it exists).
You can set multiple array values of an array like this. Perhaps it even works without the first line.
$a = array();
$a['key1'] = $a['key2'] = 'blablabla';
Or initialize the desired keys using this awkward syntax:
$a = array_fill_keys(array('key1', 'key2'), 'blablabla');
Although the second one works, I wouldn't use it. Better to use a couple of characters extra or even separate lines than to write such a weird line which doesn't have much benefit apart from saving a tiny bit of code.
I'm looking forward a solution to replace multiple values from one of my variable ($type)
This variable can have 34 values (strings).
I would like to find a way to create a new variable ($newtype) containing new strings from the replacement of my $type.
I think using str replace would be a good solution, but the only way I see things is creating a big "If ..." (34 times?) but does not seem the best way..
Thanks in advance for you help.
Best regards.
I would advise against storing a string on multiple values in a variable as it will just get messy!
Store variables in an array in the following way
$type['value1'] = 'cheese';
$type['value2'] = 'ham';
Then if you need to change it you can just do
$type['value2'] = 'chicken';
and you will get (if using print_r)
Array
(
[value1] => cheese
[value2] => chicken
}
This means all your values will be neatly stored next to a relevant key and be easily accessable as part of an individual request
echo $type['value1']
which will echo out
Cheese
You can use preg_replace with arrays:
$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2';
$to[2]='to3';
$newtype=preg_replace($from, $to, $type);
I have never used it like this but the documentation says that you need to use ksort to correctly match the order of the replaces:
$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2';
$to[2]='to3';
ksort($to);
ksort($from);
$newtype=preg_replace($from, $to, $type);
I have PHP $_SESSION arrays that have an undefined amount of elements. Is it possible to initialise all the values to 0, or do I have to check whether the value is NULL and then set to 0 every time I check a value?
Edit: I'm sorry for the vagueness of my question.
I have an undefined amount of levels, and I'd like to store all the scores of each level in that array. Currently my amount of levels is fixed, so I am currently just writing:
$_SESSION['totals'] = array(0,0,0,0,0);
And then when adding manipulating the data, I simply increment/add a certain amount to that element.
Now I'd prefer to have the same ease of directly incrementing/adding values to certain elements without needing to check whether a value is NULL or something like that...
Edit 2: edited my code as follows:
$_SESSION['totals'] = array();
if(array_key_exists($row['level']-1,$_SESSION['totals'])){
$_SESSION['totals'][$row['level']-1]++;
}else{
$_SESSION['totals'][$row['level']-1] = 1;
}
And it seems to work. Thanks fellas!
You can use array_fill_keys function to fill an array with specified value for defined keys:
$keys = array('foo', 'bar', 'baz');
$output = array_fill_keys($keys, 0);
Defining an array with initial values is defining an array with a length. This does not prevent you from adding or removing elements from the array:
// initial array
$myArray = [0, 0, 0, 0];
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0)
$myArray[] = 1;
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 1 )
$_SESSION contains only what you put into it. Just make sure you add 0 instead of null the first time you add something.
If you need to do this later, I think your design might be bad. But anyway, $_SESSION is like a normal array, so you can just use PHP's array function to traverse the array and check or change each value.
PHP arrays aren't really arrays you might know from other languages. They really are more like linked lists with hash access.
What this means is: You either know all the string array indices you want to use, and either make sure they exist, or you check their existence every time you access them which might fail.
For numeric indices, the same thing applies. You might have an array with indices 1, 2 and 4 present, but if you run over it with only a for loop, you will trigger a notice when accessing the nonexistant element 3.
Use foreach loops whenever you want to iterate arrays. Check with isset() whenever you want to document that the array value might not be present. Don't do it if you know or assume that the array element MUST be present - if not, you get the notice as a reminder that your code is working on a data structure that is NOT what you thought it is. Which actually is a good thing. Then fix it. :)
Your best bet would be to abstract your session stuff by creating facade methods, or getters and setters around the session variables rather than access them directly. This way you can return a default value if the one you're after doesn't exist.
I've used array_key_exists() to check if the index is set. If it is not, I display 0 or add store a certain value in that field, else I show the value of that index or add certain value to that field.
Credit to Sven for bringing that up.
to check what u have in your sessions, loop tru it. not sure if this is what u are asking.
foreach($_SESSION as $x=>$y)
{
if(empty($x)) { //do something }
}
I am new to php. I was wondering how I could declare a static array in php. Here is what I would do in C. How is the corresponding php code for it?
char a[][] = { (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3) };
From what I read it has to be something like this -
$a = array( 1 => array(1,1), 2 => array(1,2), ... );
Is this correct? If so it sucks :) I hope I am wrong.
Thanks,
- Pav
You've already found the way to do it natively.
Another option would be to declare your data as JSON (a very concise and human-friendly format). This could be either in a separate file bundled with your app, or directly in your code in a string. Then parse the JSON at runtime. Since PHP isn't exactly known for speed, this may or may not make your noticeably app slower to start.
you have it already figured out in your question.
One thing I would add is that you do not need to explicitly define the keys if you are intending to use a zero based array, this is assumed and can be done like so...
$a = array(array(1,1),array(1,2), ... );
You can also use what is called associative arrays which use string keys and you define them the same way you do in your example, except use strings instead of numbers...
$ass_array = array( 'array_1' => array(1,1), 'array_2' => array(1,2), ... );
you would then call your associative array like this...
$ass_array['array_1'];
Also, if you want to append single items to an array (for example in a loop to load an array)...
$ass_array[] = $item;
Further to jondavidjohn's anwser, you could just write a quick script to grab your list of values and generate the array statement for you.
No need to care how verbose the syntax is then. If the task is long and repetitious enough to care, don't do it by hand. :)
Does anybody know, how it can be, that this code echoes yahoo? There is clearly no 4th array with the key 'something', but it keeps thinking it's like that. Bug? Feature?
$array = array('a' => array('b' => array('c' => 'test')));
echo '<pre>';
var_dump($array);
echo '</pre>';
if (isset($array['a']['b']['c']['something'])) {
echo 'yahoo';
}
Because PHP thinks you are checking the 'something'th place of the string 'test'. Remember, strings are arrays of characters. try to echo $array['a']['b']['c']['something'].
::EDIT::
I Explained it, I didn't say it made sense. :P
Here has discussed the behavior of PHP in this issue and provides a solution that is exactly for your problem.
You'd want to use is_array($array['a']['b']['c']) rather than isset($array['a']['b']['c']['something']) in this case, or maybe a crafty combination of the two to make sure you don't get any errors if it's not set when you're checking to see if it's an array.
Something like:
if(isset($array['a']['b']['c']['something']) && is_array($array['a']['b']['c'])){ [...] }