I have created a session array as
$_SESSION[yans]=array();
I wish to initialize first 5 elements of this to 0.How it can be done?
As every on suggested above, try this:-
<?php
session_start();
$_SESSION['yans'] = array('A','B','C','D','E');
echo "<pre/>";print_r($_SESSION);die;
?>
Output:- http://prntscr.com/7btkxv
Note:- it's a simple example given for your understanding. thanks.
You can use the array_fill function to achieve this:
$_SESSION['yans'] = array_fill(0, 5, 0);
You should also remember to quote the yans, otherwise PHP will raise a NOTICE (unless yans is actually a defined constant).
Related
Let's say I have a function returning the following array:
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
And I'd like to assign the third and forth array elements to a variables without using of temporary variable:
list(NULL,NULL,$banana,$pear) = fruits();
This code will not work, but it will show the idea of the way I'd like to use list construction.
The reasons I'd like to use list is the following:
I use PHP 5.3 so construction like fruits()[2] will not work.
I can do more assigns within one line of fairly readable code
I'd like to skip temporary variables to reduce code size and increase its readability.
So is there any possibility to use list and skip some array elements?
php 5.5.14
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
list(,,$banana,$pear) = fruits();
echo $banana; // banana
Yes, you can skip elements: just omit the variable name:
list(,,$banana,$pear) = fruits();
PHP 7.1+
[,,$banana,$pear] = fruits();
I tried to find a proper and explanatory title but I couldn't and I will try to explain what I am asking here:
Normally if you don't assign an empty array to a variable, you can start assign values to indexes like this:
$hello["world"] = "Hello World";
...
echo $hello["world"];
but I always encounter such definition:
$hello = array() //assigning an empty array first
$hello["hello"] = "World";
...
echo $hello["hello"];
Why is it used a lot. Is there a performance gain or something with the second one?
Thanks.
Two reasons:
Better readability (you know the array is initialized at this point)
Security - when running on a system with register_globals enabled a user could add e.g. hello[moo]=something to the query string and the array would already be initialized with this. $hello = array(); overwrites this value though since a new array is created.
Initializing your variables is good practice.
Take for example this:
$foo = 'bar';
// 10 lines and 1 year later
$foo['baz'] = 'test';
Congratulations, you now have the string "tar".
This may happen accidentally and introduce needless bugs. It gets even worse with conditional variable creation. It's avoided easily by getting into the good habit of explicitly initializing your variables.
$hello = array();
if(someConditionIsTrue){
$hello["world"] = "Hello World";
}
foreach($hello as $val){ // this will not give you any error or warning.
echo $val;
}
But
if(someConditionIsTrue){
$hello["world"] = "Hello World";
}
foreach($hello as $val){ // this will give you error .
echo $val;
}
If I remember correctly, the first one will produce a warning by PHP if you have error_reporting as E_ALL. You should always use the second method because it explicitly initialises a new array. If you are looking through code and out of nowhere see $hello["hello"] but cannot recall seeing any reference to $hello before, it would be confusing.
The same will happen if you do $hello[] = "World", a warning will be displayed
In PHP I can say:
print_r($var);
What I can't do (at least I don't know how) is:
$var_info = print_r($var);
How can I accomplish the effect of putting the results of a print_r inside a variable?
PHP v5.3.5
When the second parameter is set to
TRUE, print_r() will return the
information rather than print it
$var_info = print_r($var,true);
$var_info = print_r($var, true);
Can this be done in 1 line with PHP?
Would be awesome if it could:
$out = array("foo","bar");
echo $out[0];
Something such as:
echo array("foo","bar")[0];
Unfortunately that's not possible. Would it be possible like this?
So I can do this for example in 1 line:
echo array(rand(1,100), rand(1000,2000))[rand(0,1)];
So let's say I have this code:
switch($r){
case 1: $ext = "com"; break;
case 2: $ext = "nl"; break;
case 3: $ext = "co.uk"; break;
case 4: $ext = "de"; break;
case 5: $ext = "fr"; break;
}
That would be much more simplified to do it like this:
$ext = array("com","nl","co.uk","de","fr")[rand(1,5)];
Why not check out the array functions on the PHP site?
Well, if you're picking a random element from the array, you can use array_rand().
$ext = array_rand(array_flip(array("com","nl","co.uk","de","fr")));
echo array_rand(array_flip(array('foo', 'bar')));
array flip takes an array and swaps the keys with the values and vice versa. array_rand pulls a random element from that array.
You can use a shorthand form to keep things on one line and avoid creating an array that will never be used again.
echo rand(0,1) ? rand(1,100) : rand(1000,2000);
Yes, list a PHP language construct that allows the syntax below.
list( $first_list_element ) = array( "foo", ..... );
EDIT:
Still Yes, Missed the echo. Reset will return the first array item, which might not always be index 0, but if you create an array normally it will.
echo reset( array( "foo",... ) );
EDIT AGAIN:
After you updated your question I see that you want something that PHP just can't do well. I personally think it's a syntax design error of the PHP language/interpreter. If you just mean one-line you could do.
$array = array( .... ); echo $array[0];
I think your example may not be the best. The real syntax limitation here is that one can not immediately perform array access on the returned value of a function call, as in,
do_something_with(explode(',', $str)[0]);
And you pretty much can't get around it. Assign to a variable, then access. It's a silly limitation of PHP, but it's there.
You can technically do,
function array_access($array, $i) {
return $array[$i];
}
do_something_with(array_access(explode(',', $str), 0));
But please don't. It's even uglier than an extra variable asignment.
(Given the edit to the question, this no longer a sufficient answer. However, I will leave it up for reference.)
Like #Matchu's answer, this addresses the more general case, ie you have an array value that came from somewhere, be it a function call, an instantiated array, whatever. Since the return value from an arbitrary function is the least specific case, I'll use a call to some_function() in this example.
$first_element = current(array_slice(some_function(), 0, 1));
So you could randomize it with
$random_element = current(array_slice(some_function(), rand(0,1), 1));
but in that case (as in many in php) there is a more specialized function for that; see #animuson's answer.
edited
changed array_shift() call to current() call: this is more efficient, because array_shift() will modify the intermediate array returned by array_slice().
This is being discussed in the internals mailing list right now. You might want to check it: http://marc.info/?l=php-internals&m=127595613412885&w=2
print $a[ array_rand($a = array('com','nl','co.uk','de','fr')) ];
please see: http://pastebin.com/5za3uCi1
I'm quite new to php and I'm editing the ventrilo status script. What I'd like it to do is that it stores everything in one big variable for easy parsing instead of using separate echo's. Can someone tell me how I can accomplish this?
Thanks,
Dennis
You can use the output buffer and get the contents of it:
ob_start();
echo 'foobar';
$contents = ob_get_contents(); // now contains 'foobar'
ob_end_clean();
declare a variable at the beginning, say $data or whatever. then, replace the echo calls:
echo "hello";
with this:
$data .= "hello";
then return the $data variable at the end of the function.
Instead of the echo, you can use a simple affectation :
$request = "CVentriloStatus->Request() failed. <strong>$stat->m_error</strong><br><br>\n";
But you'll soon have issues to manage multiple variables.
You could create an object to handle and store your information, but If you need something easy to set up and simple to operable, I'd go for arrays :
$ventriloStatus = array();
$ventriloStatus['requestObj'] = $stat->Request();
$ventriloStatus['requestMsg'] = "CVentriloStatus->Request() failed. <strong>$stat->m_error</strong><br><br>\n";
Add your data using keys.
Then retrieve the value easily :
echo $ventriloStatus['requestMsg'];
You can even parse your data using a simple loop
foreach($ventriloStatus as $key => $value){
echo $key.' : '.$value.'<br />';