Can Indexed Arrays be used as associative arrays? - php

I know that in PHP an indexed array that looks like:
$array = ("hello", "world")
is the same as an associative array that looks like:
$array = (0 => "hello", 1 => "world");
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
my thinking is that it translates to
$hello = $array[0]
, which will equal
$hello = "hello"
. In other words, will
$array["hello"]
equal 0?

No, you cannot fetch a key of some array element by its value right away... unless you switch keys and values with array_flip:
$arr = array('hello', 'world');
$arr = array_flip($arr);
print $arr['hello']; // 0

Let's walk through the thinking:
$array = ("hello", "world") // This is implicitly indexed by integer.
is the same as:
$array = (0 => "hello", 1 => "world"); // Explicit indexing.
You can verify by doing print_r($array); In either case, the output would show an indexed array. PHP arrays are all associative. Even if you did not specify a key, the values in an array are ordered by integer index numbers.
Now let's take a look at:
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
This is where the code will break. Why?
$array["hello"] is not a valid value. What this is referencing is "the value of the array's list at index "hello".
However, array("hello", "world") does not have an index key of "hello". Rather, it has a value "hello" which has implicitly the key index 0.
Make sure to read up on PHP arrays and understand that:
PHP arrays are all associative; keys can be strings, or if not explicitly set, will be integers.
Associative arrays are in the form of key => value pairs. If you have a key, you can find the value associated with it.
When trying to get a value from a PHP array, the syntax is: $array['key'] or in the case of multidimensionals $array['firstlevelkey']['secondlevelkey'] etc. The value that gets returned would be the value of the key => value pair at that particular key.
I hope this is helpful!

No, since "hello" is not a valid key in $array.
You can check if a key exist using array_key_exists(key,*array*)

Related

Undesired reordering of keys in PHP array

I have a quick question. When building an associative array key casting rules mean that strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. (On the other hand "08" will not be cast, as it isn't a valid decimal integer.) See for example: http://php.net/manual/en/language.types.array.php
The problem I have is that my keys are mixed integer and string .. meaning that when the associative array is built, all keys are reordered with numerical keys appear first before string. This is a sample of what I get in my console log:
...
2032: "9371.84"
2033: "9351.60"
2034: "9331.36"
2035: "9311.12"
ID: "1"
Misc1: "Russian Federation - Conventional"
Misc2: "RUS.Con1"
Misc3: "4"
Misc4: ""
... etc.
How can I avoid this issue, so that the associative array does not re-order my keys?
As an FYI, this is how I generate my array in PHP:
while ($array = mysqli_fetch_assoc($result)) {
$experiment[] = $array;
};
Thank you for your time,
G.
Adding an index to an array in PHP like this:
$array[] = ['another array'];
Will increment the indexes.
You can however specify a string for the key, or cast the integers to strings.
The workaround for the issue I have found is to avoid the associative array structure. This is what my loop looks like now:
while ($array = mysqli_fetch_assoc($result)) {
$experiment[0] = array_keys($array);
$experiment[] = array_values($array);
};
The annoying thing is that $experiment[0] = array_keys($array); gets looped uneccessarily... but at least I get the result that I am looking for and the keys are not cast and re-ordered by the associative array.
If anybody knows how to avoid the unecessary looping for $experiment[0], then please let me know :-)

Convert Array into Key Value Pair array

I have a comma separated string which i explode into an array. If the array is of un-known length and i want to make it into a key value pair array where each element in the array has the same key, how do i do this? i'm assuming i'd have to use array_combine? can anyone give me an example using the array bellow? :
for instance:
array([0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape)
into:
array([animal]=>zebra, [animal]=>cow, [animal]=>dog, [animal]=>monkey, [animal]=>ape)
You can't use the same key for each element in your array. You need a unique identifier to access the value of the array. When you use animal for all, what value should be used? What you can do is to make a 2 dimensional array that you have an array inside an array:
array(
[animals] => array(
[0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape
)
)
this can be used with $array['animals'][0]
But still you need numbers or unique identifiers to access the values of the array.
Something like this:
$string = 'zebra,cow,dog,monkey,ape';
$array = explode(',', $string);
$arrayReturn['animals'] = $array;
print_r($arrayReturn);
u cant have same key for all the values but u can do this
lets say your string is
$a = 'dog,ant,rabbit,lion';
$ar = explode(',',$a);
$yourArray = array();
foreach($ar as $animals){
$yourArray['animals']=$animals;
}
Now it doesnot matter how long your string is you will have you array as
$yourArray['animals'][0]='dog'
$yourArray['animals'][1]='ant'
....... so on ......

json in perl deserialization length count doesn't work

How do iterate through a deserialized json string? I can't get the right number of values right now it doesn't count right.
my $list = request("http://localhost/getjson.php");
my $deserialize = from_json( $list );
print Dumper($deserialize);
$VAR1 = [
'ab',
'cc',
'de',
'aer',
'ffe',
'cer',
'dad',
'efef',
'afaf',
'ege',
'grsc',
'cegg',
'cegg',
'cegg/aaa.html',
'eggt',
'ttt'
];
print length($deserialize);
13 ?? it should say 16
You are getting back an array reference not an array. You need to dereference the value.
my #array = #$deserialize; # or #{ $deserialize }
print scalar #array;
Moreover, if you want to iterate over the array you can just use for
for (#$deserialize) {
# do stuff
You are actually working with reference to the results. Since JSON can contain all sorts of different results, decode_json won't return a list specifically.
So you need to dereference the variable that you have: $deserialize
Additionally, you don't really want to be using the length function. If you print the integer value (or scalar value) of an array, it will return it's size.
So here's what you want:
my $list = request("http://localhost/getjson.php");
my $deserialize = from_json( $list );
print scalar (#{$deserialize});
That will print the size of the array.
If you want to just start by working with an array you can do:
my $list = request("http://localhost/getjson.php");
my $deserialize = from_json( $list );
my #json_array = #{$deserialize});
print scalar (#json_array);
From perldoc -f length:
This function cannot be used on an entire array or hash to find
out how many elements these have. For that, use "scalar
#array" and "scalar keys %hash", respectively.
You cannot use length to find out the size of an array. To do that, use the advice above.
Your bug gives you a false value because you are taking the length of the array reference, which in string context will be something like ARRAY(0x22d0a88), which in your case seemed to be 13 characters long. E.g. the equivalent of:
print length "ARRAY(0x22d0a88)";
As a curious side note, if you would do length(#array), it will actually return the length of the length of the array. E.g. an array of size 16 would return 2, because the string "16" is two characters long.

php compare array keys, not values

I am successfully using the array_key_exists(), as described by php.net
Example:
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
But, take out the values, and it doesn't work.
<?php
$search_array = array('first', 'second');
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
Not sure how to only compare 2 arrays by their keys only.
The first example is an associative array: keys with values assigned. The second example is just a prettier way of saying:
array(0 => 'first', 1 => 'second')
For the second, you would need to use in_array. You shouldn't check for the presence of a key, which array_key_exists does, but rather the presence of a value, which in_array does.
if(in_array('first', $array))
In PHP, each element in a array has two parts: the key and the value.
Unless you manually say what keys you want attached to each value, PHP gives each element a numerical index starting at 0, incrementing by 1.
So the difference between
array('first','second')
and
array('first'=>1,'second'=>4)
is that the first doesn't have user-defined keys. (It actually has the keys 0 and 1)
If you were to do print_r() on the first, it would say something like
Array {
[0] => "first",
[1] => "second"
}
whereas the second would look like
Array {
["first"] => 1,
["second"] => 2
}
So, to check if the key "first" exists, you would use
array_key_exists('first',$search_array);
to check if the the value "first" exists, you would use
in_array('first',$search_array);
in the second example, you didn't assign array keys - you just set up a basic "list" of objects
use in_array("first", $search_array); to check if a value is in a regular array
In your second example the keys are numeric your $search_array actually looks like this:
array(0=>'first', 1=>'second');
so they key 'first' doesnt exist, the value 'first' does. so
in_array('first', $search_array);
is the function you would want to use.
In PHP, if you are not giving key to array element they take default key value.Here you arrray will be internally as bellow
$search_array = array(0=>'first', 1=>'second');
Anyway you can still fix this problem by using the array_flip function as below.
$search_array = array('first', 'second');
if (array_key_exists('first', array_flip($search_array))) {
echo "The 'first' element is in the array";
}

return last numeric key (NOT value) of an array?

I have an array like this:
array[0] = "hello0"
array[1] = "hello1"
array[2] = "hello2"
Now I want to get the last key '2' of the array. I cant use end() because that will return the value 'hello2'.
What function should I use?
end() not only returns the value of the last element but also sets the internal pointer to the last element. And key() returns the key of the element this internal pointer currently ...err... points to.
$a = array(1=>'a', 5=>'b', 99=>'d');
end($a);
echo key($a);
prints 99
If the keys are not continuous (i.e. if you had keys 1, 5, 7, for example):
$highest_key = rsort(array_keys($myarray))[0];
If they are continuous, just use count($myarray)-1.
count($array) - 1
Won't work if you've added non-numeric keys or non-sequential keys.

Categories