Arrays in PHP. Taking off a variable from array - php

Imagine this code:
$array1 = "20";
$array2 = "40";
$array3 = "";
$arraydate = array($array1,$array2,$array3); //In this case would be array("20","40","0")
So what I want is that when there is a variable that is null, 0 or empty, then do not make part of the array. The solution to this is to pass from:
array("20","40","0")
to:
array("20","40")
Is there anyway to do this? Sorry for my bad english. Thank you :D.

Use $arraydate = array_filter($arraydate);
According to the manual, if no callback is given, it will remove all items that equal to false.

Have you actually looked in the PHP Manual? They provide a one line solution with array_filter...
$newAray = array_filter($arraydate);

Wrong Imagination this would never result to array("20","40","0"), it would be instead
array ( "20", "40", "")
And even of you are getting that then use array_filter function to filter value

Related

PHP Value from Array

I'm trying to work out how to get values from one of three arrays based on the array name.
$ABC001 = array('A'=>'10','B'=>'2','C'=>'1.0');
$ABC002 = array('A'=>'20','B'=>'4','C'=>'1.1');
$ABC003 = array('A'=>'30','B'=>'6','C'=>'1.2');
I have a variable passed to my script it will be contain something like ABC#001 or ABC#002
I'm removing the # so the var value now matches the array name/
$test = str_replace('#','',$var);
If I do var_dump ( $$test ) I get all the values from the correct array, but if I do echo $$test['A'] or echo $$test[0] I don't get the value from the first key in the correct array.
Can someone advise how to do this.
Thanks
try this ${$test} to get the values of the array
<?php
$ABC001 = array('A'=>'10','B'=>'2','C'=>'1.0');
$ABC002 = array('A'=>'20','B'=>'4','C'=>'1.1');
$ABC003 = array('A'=>'30','B'=>'6','C'=>'1.2');
$var = "ABC#002";
$test = str_replace('#','',$var);
var_dump(${$test}['A']);
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$test['A'] then the parser needs to know if you meant to use $test['A'] as a variable, The syntax for resolving this ambiguity is: ${$test}['A'] . Please check the documention here PHP Variable Variable

Can you call a variable as a value in an array - PHP

I'm trying to get this to work, but I think the syntax is off.
How do you call a variable as a value within the array?
<?php
$password = "password1";
$USERS["username"] = "".$password."";
//would like the outcome to be: $USERS["username"] = "password1"
?>
To assign a variable to an array index, simply write:
$USERS["username"] = $password;
You should also read up this tutorial, its very useful and its explained very clearly. Good for your future reference. PHP-Arrays

PHP arrays... What is/are the meaning(s) of an empty bracket?

I ran across some example code that looks like this:
$form['#submit'][] = 'annotate_admin_settings_submit';
Why is there a bracket after ['#submit'] that is empty with nothing inside? What does this imply? Can anyone give me an example? Normally (from my understanding which is probably wrong) is that arrays have keys and in this case the the $form array key '#submit' is equal to 'annotate_admin_settings_submit' but what is the deal with the second set of brackets. I've seen examples where an array might look like:
$form['actions']['#type'] = 'actions';
I know this is a very basic question about php in general but I ran across this question while learning Drupal so hopefully someone in the Drupal community can clarify this question that I'm obsessing over.
When you say $form['actions']['#type'] = 'actions', it assigns a value to $form['actions']['#type'], but when you say $form['#submit'][] = 'annotate_admin_settings_submit', if $form['#submit'] is an array, it appends 'annotate_admin_settings_submit' to the end of it, and if it's empty, it will be an array with one single element that is 'annotate_admin_settings_submit'.
The empty brackets mean that when the string is added to the array, php will automatically generate a key for the entry instead of it being specified in the brackets when populating the array.
So $form['#submit'][] = 'annotate_admin_settings_submit'; is the same thing as $form['#submit'][0] = 'annotate_admin_settings_submit'; if it's the first time you do it.
Next time it will be $form['#submit'][1] = 'annotate_admin_settings_submit';, etc.
The empty bracket adds an auto increment index to an array. The new index will be +1 to the last index.
Please check this example.
$form['#submit'][0] = 'zero';
$form['#submit'][1] = 'One';
$form['#submit'][] = 'Two'; // this will be considered as $form['#submit'][2] = 'Two';
$form['#submit'][4] = 'Four';
$form['#submit'][] = 'Four'; //this will be considered as $form['#submit'][5] = 'Four'; since its adds 4(last index)+1

PHP get array() value to become $variable

ok, So I have this array:
$choices = array($_POST['choices']);
and this outputs, when using var_dump():
array(1) { [0]=> string(5) "apple,pear,banana" }
What I need is the value of those to become variables as well as adding in value as the string.
so, I need the output to be:
$apple = "apple";
$pear = "pear";
$banana = "banana";
The value of the array could change so the variables have to be created depending on what is in that array.
I would appreciate all help. Cheers
Mark
How about
$choices = explode(',', $_POST['choices']);
foreach ($choices as $choice){
$$choice = $choice;
}
$str = "apple,pear,pineapple";
$strArr = explode(',' , $str);
foreach ($strArr as $val) {
$$val = $val;
}
var_dump($apple);
This would satisfy your requirement. However, here comes the problem, since you could not predefine how many variables are there and what are they, it's hard for you to use them correctly. Test "isset($VAR)" before using $VAR seems to be the only safe way.
You'd better just split the source string in just one array and just operate the elements of the specific array.
I have to concur with all the other answers that this is a very bad idea, but each of the existing answers uses a somewhat roundabout method to achieve it.
PHP provides a function, extract, to extract variables from an array into the current scope. You can use that in this case like so (using explode and array_combine to turn your input into an associative array first):
$choices = $_POST['choices'] ?: ""; // The ?: "" makes this safe even if there's no input
$choiceArr = explode(',', $choices); // Break the string down to a simple array
$choiceAssoc = array_combine($choiceArr, $choiceArr); // Then convert that to an associative array, with the keys being the same as the values
extract($choiceAssoc, EXTR_SKIP); // Extract the variables to the current scope - using EXTR_SKIP tells the function *not* to overwrite any variables that already exist, as a security measure
echo $banana; // You now have direct access to those variables
For more information on why this is a bad approach to take, see the discussion on the now deprecated register_globals setting. In short though, it makes it much, much easier to write insecure code.
Often called "split" in other langauges, in PHP, you'd want to use explode.
EDIT: ACTUALLY, what you want to do sounds... dangerous. It's possible (and was an old "feature" of PHP) but it's strongly discourage. I'd suggest just exploding them and making their values the keys of an associative array instead:
$choices_assoc = explode(',', $_POST['choices']);
foreach ($choices as $choice) {
$choices_assoc[$choice] = $choice;
}

Can this be done in 1 line?

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')) ];

Categories