Look at this code:
$a = array('1'=>'1');
$b = array(''=>'');
var_dump(array_merge($a,$b));
the output seems really strange to me:
array(2) {
[0] =>
string(1) "1"
'' =>
string(0) ""
}
Ok, I've changed $a into this: $a = array('k'=>'v'); and the output became more predictable:
array(2) {
'k' =>
string(1) "v"
'' =>
string(0) ""
}
The question is: why the hell the key of the first element is 0 in the first example?
edit:
var_dump($a);
array(1) {
[1] =>
string(1) "1"
}
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
http://php.net/array_merge
Yes, it's an idiosyncrasy of PHP to treat numeric string values as numeric values in this case. You may want to use $a + $b instead.
Related
I'm studying php and I'm trying to figure out how to get the string "Juve_Milan" from this var_dump($_POST) :
array(5) {
["Juve_Milan"] => array(2) {
[0] => string(1)
"5" [1] => string(1)
"1"
}["Inter_Roma"] => array(2) {
[0] => string(1)
"4" [1] => string(1)
"4"
}["Napoli_Lazio"] => array(2) {
[0] => string(1)
"2" [1] => string(1)
"5"
}["name"] => string(0)
"" ["submit"] => string(5)
"Invia"
}
I could get all of them with:
foreach ($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td><td>".$param_val[0]."-".$param_val[1]."</td></tr>";
}
But i want to get them exactly one by one, for example, if i want to get the string "Juve_Milan" or "inter_Roma" how can i do?
Without looping, how can i get the string value: "Juve_milan" or "Inter_Roma"? Becouse with the loop i can access them this way : $_POST as $param_name => $param_val
But i want to get them without loop, my first attempt was something like $_POST[0][0] but its wrong...
There are numbers of php array functions you can use.
You can use
array shift
to remove an element from an array and display it .e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
$juve = array_shift($club);
echo $juve;// 'juve_millan'
but note that the array is shortened by one element i.e. 'juve_millan' is no more in the array and also note that using
array_shift
over larger array is fairly slow
Array Slice function
PHP
array_slice()
function is used to extract a slice of an array e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
if I want to display
inter_roma
or assigned it to a variable, then I can do this
$roma = array_slice($club, 1, 1);// The first parameter is the array to slice, the second parameter is where to begin(which is one since most programming language array index start from 0 meaning juve_millan is zero, while inter_roma is 1, napoli_lazio is 2) and the length is 1 since i want to return a single element.
I hope you understand
You could iterate over keys of the main array like this:
foreach($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td></tr>";
}
This will return each Juve_Milan, Inter_Roma etc. one by one. Although it's part of the code you already have, I believe this will return values you want only.
array(24) { ["user_id"]=> string(1) "9" ["facebook_id"]=> string(15) "381305418721463" ["first_name"]=> string(4) "John" ["last_name"]=> string(4) "Does" ["current_latitude"]=> string(10) "-37.825697" ["current_longitude"]=> string(10) "144.999965" ["current_address"]=> string(45) "229 Swan Street, Richmond VIC 3121, Australia" ["date_of_birth"]=> string(10) "01/01/1990" ["city"]=> string(30) "Melbourne, Victoria, Australia" ["country"]=> string(0) "" ["email_address"]=> string(22) "bzingatester#gmail.com" ["profile_pic"]=> string(0) "" ["first_login"]=> string(2) "no" ["blocked_users_id"]=> string(0) "" ["my_friend"]=> string(52) "10152805813948795,10155307822515151,1389504958030240" ["search_radius"]=> string(2) "50" ["device_type"]=> string(3) "ios" ["device_id"]=> string(1) "1" ["device_token"]=> string(64) "6ddaf9d59418e99b1c9cb28c21d94647bfed9f78a80b410164c1f2798beee84a" ["hideFromActivityFeed"]=> string(2) "no" ["hideFromFriendsofFriends"]=> string(2) "no" ["hideNotification"]=> string(2) "no" ["created_date"]=> string(19) "2015-01-07 01:00:11" ["modified_date"]=> string(19) "2015-02-27 05:36:12" }
In PHP I have an array called $userData as per above, I want to be able to echo values such as first name 'first_name', using code like this
echo $userInfo->first_name;
(this doesnt seem to work)
I DO NOT want to loop and fetch all keys in array using foreach, just get values 'first_name', 'last_name' ect. from the array
Please try like this,
$first_name = $userInfo['first_name'] // $userInfo is array name
You can change the array to object and then use -> like below
$userData= (object) $userData;
And then
$userData->firstName ..etc
Please use type casting.
$userinfo = (array)$userInfo;
Then you access your key first_name.
echo $userinfo['first_name'];
First of use a different method to dump data ..
echo "<pre>";
print_r($your_array);
exit;
It just simply bodes for a better presentation to see what is an object and what is an array.
You cannot access array members with the object notation. You can however cast your array as an object.
(object)$yourarray;
If you want to access array members, use :
$yourarray['first_name'];
If you cast as an object:
$obj = (object)$yourarray;
Now access:
$obj->firstname;
Hope that helps.
Actually we use arrays in programming to prevent loop or something like this to find a value, so instead of this structure,
$a = 'text1';
$b = 0;
$c = true;
$d = 'text2';
we use arrays:
$array = array('a' = > 'text1', 'b' => 0, 'c' => true, 'd' => 'text2' );
and to access the value of some key, we call the key name, inside brackets after array's name:
echo $array['a'];
//will echo text1
//or
echo $array['b'];
//will echo true
This is associative array...
if you just pass values to an array without keys, php will use numeric keys instead...
$array = array( 'text1', '0', true, 'text2' );
$array[0] = 'text1';
$array[1] = 0;
$array[2] = true;
$array[3] = 'text2';
I am new to PHP and arrays and am wanting to understand the following array. I would also like to learn how I would go about assigning values to two particular array elements in PHP, i.e.:
["_gravity_form_lead"]=> array(5) { [1]=> string(4) "1000" [3]=> string(6) "strips" [2]=> string(2) "rp" [5]=> string(0) "" [6]=> string(0) "" }
1) What is the correct notation to define this array?
2) For the two array elements that are "", i.e.
[5]=> string(0) "" [6]=> string(0) ""
In PHP, how would I go about assigning values to these two array elements, that are NULL?
Hope this makes you understand ,
$array_before = array('_gravity_form_lead' => array( '1000', "strips", "rp", '', ''));
echo '<pre>';
echo 'This what it looks after print_r'.'<br>';
print_r($array_before);
echo '</pre>';
I don't see anything different and special than its said in the documentation
http://php.net/manual/en/language.types.array.php
Anyway, the concrete situation is.
$_gravity_form_lead = array(1=>1000, 3=>'strips', 2=>'rp', 5=>'', 6=>'');
As said in the documentation
Creating/modifying with square bracket syntax ΒΆ
An existing array can be modified by explicitly setting values in it.
This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).
$arr[key] = value;
You do modify the ones you need with [ ]
In this particular case:
$_gravity_form_lead[5] = 'something';
$_gravity_form_lead[6] = 'something else';
In order you want to modify all empty strings, you can iterate through the array and modify. You have two options while iterating - using reference &, which will modify the existent one, or creating new array.
foreach ($_gravity_form_lead as &$val) {
if ($val == '') {
$val = 'something';
}
}
The output after doing this is
var_dump($_gravity_form_lead);
/*
* array (size=5)
1 => int 1000
3 => string 'strips' (length=6)
2 => string 'rp' (length=2)
5 => string 'something' (length=9)
6 => &string 'something' (length=9)
*/
It would be defined somewhat like,
$arrayName = array('_gravity_form_lead' => array( 1=>'1000', 3=>"strips", 2=>"rp", 5=>'', 6=>''));
/* assign null instead of '' */
$arrayName['_gravity_form_lead'][5] = NULL;
$arrayName['_gravity_form_lead'][6] = NULL;
PHP documentation states that the default value of array_keys second argument is NULL.
However, when passing NULL explicitly, array_keys does not seem to work properly.
Example:
code
$a = array(10=>'a', 11=>'b', 12=>'b', 13=>'c', 14=>'c', 15=>'b');
$keys = array_keys($a);
var_dump($keys); //Output 0
$keys = array_keys($a, null);
var_dump($keys); //Output 1
Output
array
0 => int 10
1 => int 11
2 => int 12
3 => int 13
4 => int 14
5 => int 15
array
empty
Question
I reckon it must be trying to find keys whose value is null.
Passing false or empty string produces the exact same behavior (obviously).
So, what is the default value?
Answer
xdazz answer is right. When inspecting the C code of this function, my first though was that this was a bad implementation at C level (and easily fixed by removing code)
But then I realized this is actually the intended behavior since they went to a lot of trouble to enable you to test for NULL values inside the array.
The default value is hard to explain here.
It is special case, the default value of second parameter is not actually the php's NULL, but the C level's NULL.
Dive into the source code:
PHP_FUNCTION(array_keys)
{
zval *input, /* Input array */
*search_value = NULL, /* Value to search for */
//....
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) {
return;
}
// ....
You could see, the default value is NULL for search_value, but if you specified the second parameter of array_keys, then after zend_parse_parameters, search_value will not be NULL.
I agree with xdazz. However, it seems that passing 0 works. Don't ask me how, though! (And, YMMV.)
$a = array(10=>'a', 'xaa'=>'b', 12=>'b', 13=>'c', 14=>'c', 15=>'b');
$keys = array_keys($a, 0);
var_dump($keys); //Output 0
Returns:
array(6) { [0]=> int(10) [1]=> string(3) "xaa" [2]=> int(12) [3]=> int(13) [4]=> int(14) [5]=> int(15) }
Since you're searching for null, there's no result to give back to you :)
It is hard to infer from PHP manual as to the use of search_value parameter. I needed to do try an example.
If the optional search_value is specified,
then only the keys for **that** value are returned.
Otherwise, all the keys from the input are returned.
It means that when search_value is specified in array_keys(), the values in the array (not keys) are searched against search_value. If match occurs, the key for that value in search_value is returned.
Example
<?
$foo = array('first' => 'my_first',
'second' => 'my_second',
'third' => 'my_third',
'fourth' => null);
$keys = array_keys($foo);
var_dump($keys); //Output 0
$keys = array_keys($foo, 'my_second');
var_dump($keys); //Output 1
$keys = array_keys($foo, null);
var_dump($keys); //Output 2
?>
Output
0:
array(4) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
[2]=>
string(5) "third"
[3]=>
string(6) "fourth"
}
1:
array(1) {
[0]=>
string(6) "second"
}
2:
array(1) {
[0]=>
string(6) "fourth"
}
I have this kind of array:
$a = array(
'one' => 'one',
'0' => '0',
'two' => 'two',
'three' => 'three',
'four'
);
as you can see it is an associative array BUT not all the keys have the value (take a look at the last).
My question is, how can i loop this kind of array to get key(if exists) and the respective value?
Thank you!
The string 'four' in your example is not a key but a value. The corresponding key will be 1. This happens because PHP converts the string key '0' to numeric key 0 and for the value 'four' it uses the next numeric key which will be 1.
Reference:
A key may be either an integer or a string. If a key is the standard
representation of an integer, it will be interpreted as such (i.e. "8"
will be interpreted as 8, while "08" will be interpreted as "08")
To have a key with no value you can use NULL as the value:
'four' => null
Similarly to have an empty key use null as key:
null => 'four'
And to loop over such an array you can use a foreach loop. To detect if a key/value is null or not you can use the isset function.
With var_dump($a); you see all keys and values:
array(5) {
["one"] => string(3) "one"
[0] => string(1) "0"
["two"] => string(3) "two"
["three"] => string(5) "three"
[1] => string(4) "four"
}
you can use the foreach construction:
foreach($a as $key=>$val){
// $key is a current key
// $val is tha current value associated
}
As described in PHP: Arrays
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.
So you cannot distinguish key '0' and 0. And your last element is not a key, it is a value with auto incremental integer key 1. You can check with var_dump($a):
array(5) {
["one"]=>
string(3) "one"
[0]=>
string(1) "0"
["two"]=>
string(3) "two"
["three"]=>
string(5) "three"
[1]=>
string(4) "four"
}
If you can ensure all your keys do not start with digit, then you can just iterate the array as usual, and test the key using is_int.