in php 4.4.4 having:
$hbc=pack("LL",82603088,82602992);
list($v1,$v2)=unpack("L2",$hbc);
echo("v1=".$v1." v2=".$v2);
result is:
v1= v2=82603088
I already have some hours wrapping my head aroud this...
thanks
The error is not withing the pack or unpack, but inside the list().
Turn on notices! Your code will complain like this:
Notice: Undefined offset: 0 in ...
That should make you wonder. If you dump the array that is returned by unpack, it is correct:
array(2) {
[1] =>
int(82603088)
[2] =>
int(82602992)
}
And then there is this tiny little note on the docs page of list():
list() only works on numerical arrays and assumes the numerical indices start at 0.
Your array does not start at index 0, and the notice likes to tell you that.
The quick fix is:
list(,$v1,$v2)=unpack("L2",$hbc); // add a comma to skip index 0
A better approach might be to use unpack to create named array indices:
$unpacked = unpack("L2v/",$hbc);
Result:
array(2) {
'v1' =>
int(82603088)
'v2' =>
int(82602992)
}
From the php.net comments.
$int_list = array_merge(unpack("s*", $some_binary_data));
This will essentially reset your index keys starting at 0.
Related
This is my code, it's for have an array :
$zi = '1';
for ($zi = 1; $zi <= $v['Store']['stock']; $zi++) {
$options_array[$zi]= $zi;
}
var_dump($options_array);
Array
(
[0] => 0
[1] => 1
[2] => 2
)
why i have the zero in my result ?
i put $zi at 1, so why ?
As my comment turned out to be correct: The issue is that you already have a property 0 in the $options_array before you even get to the presented code block. You can start with a fresh array using $options_array = [] or $options_array = array() (for older php versions). You can also just remove property 0 with unset($options_array[0]).
In php there are two kinds of arrays, numerically indexed arrays, and associative arrays. Your output seems a little suspect but I can tell you that if all the keys of a PHP array are numeric then the array will be zero based.
I see how you have $zi = '1' above, which is along the lines of what you would have to do to create a one based array, but it would be associative, and you won't be able to simply use the ++ operator. I believe even if you use a string that is a number PHP will still convert to a numerically indexed array. I recommend against trying to implement a one based array, it's insanity.
Hope this page helps http://us2.php.net/manual/en/language.types.array.php
You start setting $options_array at index 1, so index 0 is whatever the default value of the underlying type is. In this case, it's an integer, so the default is 0.
When using php array_fill and negative indices, why does php only fill the first negative indice and then jump to 0.
For example:
array_fill(-4,4,10) should fill -4, -3, -2, -1 and 0 but it does -4, 0, 1, 2, 3
The manual does state this behaviour but not why.
Can anyone say why this is?
Looking at the source for PHP, I can see exactly why they did this!
What they do is create the first entry in the array. In PHP, it looks like:
$a = array(-4 => 10);
Then, they add each new entry like this:
$count--;
while ($count--) {
$a[] = 10;
}
If you do this exact same thing yourself, you'll see the exact same behavior. A super short PHP script demonstrates this:
<?php
$a = array(-4 => "Apple");
$a[] = "Banana";
print_r($a);
?>
The result: Array ( [-4] => Apple [0] => Banana )
NOTE
Yes, I did put in PHP instead of the C source they used, since a PHP programmer can understand that a lot better than the raw source. It's approximately the same effect, however, since they ARE using the PHP functions to generate the results...
Maybe because it's stated in the doc: http://www.php.net/manual/en/function.array-fill.php
If start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero (see example).
Using php's explode with the following code
$data="test_1, test_2, test_3";
$temp= explode(",",$data);
I get an array like this
array('0'=>'test_1', '1'=>'test_2', 2='test_3')
what I would like to have after explode
array('1'=>'test_1', '2'=>'test_2', 3='test_3')
You could something like this :
$temp = array_combine(range(1, count($temp)), array_values($temp));
uses array_combine() to create array using your existing values (using array_values()) and range() to create a new range from 1 to the size of your array
Working example here
Array indexes start at 0. If you really wanted to have the array start with one, you could explode it, then copy it to another array with your indexes defined as starting at 1 - but why?
You could use this possibly (untested)
$newArray=array_unshift($temp,' ');
unset($newArray[0]);
it is impossible using explode.
for($i = count($temp) - 1; $i >= 0; $i--)
$temp[$i + 1] = $temp[$i];
unset($temp[0]);
You couldn't do it directly, but this will do what you're after:
$temp=explode(',',',' . $data);
unset($temp[0]);
var_dump($temp);
array(3) {
[1]=>
string(6) "test_1"
[2]=>
string(7) " test_2"
[3]=>
string(7) " test_3"
}
Lloyd Watkin's answer makes the fewest function calls to achieve the expected result. It is certainly a superior answer to ManseUK's method which uses four functions in its one-liner after the string has been exploded.
Since this question is nearly 5 years, old there should be something valuable to add if anyone dare to chime in now...
I have two things to address:
The OP and Lloyd Watkins both fail to assign the correct delimiter to their explode method based on the sample string. The delimiter should be a comma followed by a space.
Sample Input:
$data="test_1, test_2, test_3";
No one has offered a one-liner solution that matches Lloyd's two-function approach. Here that is: (Demo)
$temp=array_slice(explode(", ",", $data"),1,null,true);
This two-function one-liner prepends the $data string with a comma then a space before exploding it. Then array_slice ignores the first empty element, and returns from the second element (1) to the end (null) while preserving the keys (true).
Output as desired:
array(
1 => 'test_1',
2 => 'test_2',
3 => 'test_3',
)
All,
I have an array with hyphens in the key name. How do I extract the value of it in PHP? It returns a 0 to me, if I access like this:
print $testarray->test-key;
This is how the array looks like
testarray[] = {["test-key"]=2,["hotlink"]=1}
Thanks
You have problems:
testarray[] = {["test-key"]=2,["hotlink"]=1}
1 2
You are missing $ used to create variables in php
It is not a valid array format
.
print $testarray->test-key;
1
The => operator is used for objects, not arrays, use [] instead.
Here is how your code should be like:
$testarray = array("test-key" => 2, "hotlink" => 1);
print $testarray['test-key'];
Finally,
See PHP Array Manual
print $testarray["test-key"];
The PHP manual has a good page explaining arrays and how to do things with them:
http://www.php.net/manual/en/language.types.array.php
Having a brain freeze over a fairly trivial problem. If I start with an array like this:
$my_array = array(
'monkey' => array(...),
'giraffe' => array(...),
'lion' => array(...)
);
...and new elements might get added with different keys but always an array value. Now I can be sure the first element is always going to have the key 'monkey' but I can't be sure of any of the other keys.
When I've finished filling the array I want to move the known element 'monkey' to the end of the array without disturbing the order of the other elements. What is the most efficient way to do this?
Every way I can think of seems a bit clunky and I feel like I'm missing something obvious.
The only way I can think to do this is to remove it then add it:
$v = $my_array['monkey'];
unset($my_array['monkey']);
$my_array['monkey'] = $v;
array_shift is probably less efficient than unsetting the index, but it works:
$my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
$my_array['monkey'] = array_shift($my_array);
print_r($my_array);
Another alternative is with a callback and uksort:
uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.
I really like #Gordon's answer for its elegance as a one liner, but it only works if the targeted key exists in the first element of the array. Here's another one-liner that will work for a key in any position:
$arr = ['monkey' => 1, 'giraffe' => 2, 'lion' => 3];
$arr += array_splice($arr, array_search('giraffe', array_keys($arr)), 1);
Demo
Beware, this fails with numeric keys because of the way that the array union operator (+=) works with numeric keys (Demo).
Also, this snippet assumes that the targeted key is guaranteed to exist in the array. If the targeted key does not exist, then the result will incorrectly move the first element to the end because array_search() will return false which will be coalesced to 0 by array_splice() (Demo).
You can implement some basic calculus and get a universal function for moving array element from one position to the other.
For PHP it looks like this:
function magicFunction ($targetArray, $indexFrom, $indexTo) {
$targetElement = $targetArray[$indexFrom];
$magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom);
for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){
$targetArray[$Element] = $targetArray[$Element + $magicIncrement];
}
$targetArray[$indexTo] = $targetElement;
}
Check out "moving array elements" at "gloommatter" for detailed explanation.
http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html