php arrays (and removing certain element) - php

I'm not 100% but this ($settings) would be called an array in php:
$setting;
$setting['host'] = "localhost";
$setting['name'] = "hello";
but what's the name for this that's different to the above:
$settings = array("localhost", "hello");
Also from the first example how can i remove the element called name?
(please also correct my terminology if I have made a mistake)

I'm not 100% but this ($settings)
would be called an array in php:
You should be 100% sure, they are :)
but what's the name for this that's
different to the above:
This:
$setting['host'] = "localhost";
$setting['name'] = "hello";
And this are different ways of declaring a php array.
$settings = array("localhost", "hello");
In fact this is how later should be to match the first one with keys:
$settings = array("host" => "localhost", "name" => "hello");
Also from the first example how can i
remove the element called name?
You can remove with unset:
unset($setting['name']);
Note that when declaring PHP array, do:
$setting = array();
Rather than:
$setting;
Note also that you can append info to arrays at the end by suffixing them with [], for example to add third element to the array, you could simply do:
$setting[] = 'Third Item';
More Information:
http://php.net/manual/en/language.types.array.php

As sAc said, they are both array. The correct way to declare an array is $settings = array(); (as opposed to just $settings; in your first line.)
The main difference between the first and second way is that the first allows you to use $settings['host'] and $settings['name'], whereas the latter can only be used with numeric indices ($settings[0] and $settings[1]). If you want to use the first way, you can also declare your array like this: $settings = array('host'=>'localhost', 'name'=>'hello');
More reading on PHP arrays

Well this is indeed an array. You have different types of array's in php. The first example you mention is called an Associative Array. Simply an array with a string as a key.
An associative array can be declared in two ways:
1) (the way you declared it):
$sample = array();
$sample["name"] = "test";
2)
$sample = array("name" => "localhost");
Furthermore the first example can also be used to add existing items to an array. For example:
$sample["name"][] = "some_name";
$sample["name"][] = "some_other_name";
When you execute the above code with print_r($sample) you get something like:
Array ( [name] => Array ( [0] => some_name [1] => some_other_name ) )
Which is very usefull when adding multiple strings to an existing array.
Removing a value from an array is very simple,
Like mentioned above, use the unset function.
unset($sample["name"])
to unset the whole name value and values connected to it
Or when you only want to unset a specific item within $sample["name"] :
unset($sample["name"][0]);
or, ofcourse any item you'd like.
So basicly.. the difference between your first example and the latter is that the first is an associative array, and the second is not.
For further reference on arrays, visit the PHP manual on arrays

Related

PHP adressing the first key in an array that changes

For example, lets say I have an array that looks liked
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
and then I call the asort() function and it changes the array around. How do I get the new first string without knowing what it actually is?
If you want to get the first value of the array you can use reset
reset($stuff);
If you want to also get the key use key
key($stuff);
If you need to get the first value, do it like this:
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
$values = array_values($stuff); // this is a consequential array with values in the order of the original array
var_dump($values[0]); // get first value..
var_dump($values[1]); // get second value..

Make string with special character to array variable php

There's
trainingData = [[3, 1],[6, 1]]
How to make trainingData an array variable?
This way you can achieve.
<?php
$trainingData = '[[3, 1],[6, 1]]';
$array = json_decode($trainingData);
//Array variable
print_r($array);
?>
I'm assuming that you come from Python (or any other language that uses that kind of array defining), then you want to know how to define an array in PHP. Then there are a lot of different ways to do this but I will give you 2 fast examples:
Option 1:
<?php
$trainingData = array(
array(3,1),
array(6,1)
);
var_dump($trainingData);
Option 2 (this one mostly used when using loops to append to arrays):
<?php
$trainingData = array();
$trainingData[] = array(3,1);
$trainingData[] = array(6,1);
var_dump($trainingData);
More information and examples you can find at php docs about Arrays

Create key => value pair array only if variables are set

I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);

php change the name to construct an associative array

Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.
EDIT -------
following Tristan's lead, I made this simple function to easily
write in json in php. It will even take on variable from within
your php as the whole thing is enclosed in quotes.
$one = 'newOne';
$json = "{
'$one': 1,
'two': 2
}";
// doesn't work as json_decode expects quotes.
print_r(json_decode($json));
// this does work as it replaces all the single quotes before
// using json decode.
print_r(jsonToArray($json));
function jsonToArray($str){
return json_decode(preg_replace('/\'/', '"', $str), true);
}
In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.
This means that you can use an array whichever way you please.
If you wanted an indexed array..
$indexedArray = array();
$indexedArray[] = 4; // Append a value to the array.
echo $indexedArray[0]; // Access the value at the 0th index.
Or even..
$indexedArray = [0, 10, 12, 8];
echo $indexedArray[3]; // Outputs 8.
If you want to use non integer keys with your array, you simply specify them.
$assocArray = ['foo' => 'bar'];
echo $assocArray['foo']; // Outputs bar.

Why can't I use integers as an index in a PHP $_SESSION array?

Eg:
$_SESSION['1'] = 'username'; // works
$_SESSION[1] = 'username'; //doesnt work
I want to store session array index as array index. So that o/p is :
Array(
[1] => 'username'
)
$_SESSION can only be used as an associative array.
You could do something like this though:
$_SESSION['normal_array'] = array();
$_SESSION['normal_array'][0] = 'index 0';
$_SESSION['normal_array'][1] = 'index 1';
Personally, I'd just stick with the associative array.
$_SESSION['username'] = 'someuser';
Or
$_SESSION['username_id'] = 23;
I suspect this is probably because the $_SESSION array is purely an associative array. Additionally, as the PHP manual puts it:
The keys in the $_SESSION associative
array are subject to the same
limitations as regular variable names
in PHP, i.e. they cannot start with a
number and must start with a letter or
underscore.
Incidentally, have you checked your error log for any NOTICE level errors? (You may have to enable this level.) Attempting to use a numeric key will quite possibly raise an error.
You can also take this approach to save an array dimension:
$_SESSION['form_'.$form_id] = $form_name;
which might look like the following:
$_SESSION['form_21'] = 'Patient Evaluation';
as opposed to:
$_SESSION['form'][21] = 'Patient Evaluation';
which uses another array dimension.

Categories