If I have an array like the following -
$numbers= array(
'One' => 1,
'Two' => 2,
'Three' => 3,
);
Is there a function I an use to add together both the values of 'One' and 'Two', and output the value?
If not, how would I go about making that simple function? (This is something i'd be interested in knowing too even if there is a predefined function.)
You have to use two array function.
array_slice() returns the sequence of elements from the array array as
specified by the offset and length parameters.
Basic Format of array_slice().
array_slice(array, start, length, preserve)
So,
start: Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array.
length:
Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
array_sum() returns the sum of values in an array.
Your array:
$numbers= array(
'One' => 1,
'Two' => 2,
'Three' => 3,
);
Function
echo $arr_sum = array_sum(array_slice($numbers, 0, 2));
Output:
3
Related
I have to pass a query parameters with different values but absolutely equal keys. I found this \GuzzleHttp\Psr7\build_query(); But it returns only last value. For instance:
$array = [
'test' => '1',
'test' => '2'
]
\GuzzleHttp\Psr7\build_query($array);
//OR
http_query_builder($array);
It returns every time string with the last item.
Does it possible to do that with PHP? Because the side which will take these parameters just can not do anything in their side so I have to pass parameters with the equal keys.
The problem was not with the specific method used, but with how you filled your array to begin with:
$array = [
'test' => '1',
'test' => '2'
]
You can not use the same array key twice; your array only contains one element now, because the second one has overwritten the existing first one under that same key.
Make the test element itself an array, that contains your two values:
$array = [
'test' => ['1', '2']
];
I have an array (as shown below). It has a and b, the numbers inside of each of them. However, when I use the end() function, it gives me b's array. I want the actual b letter. to be printed, not the number array. How can I do this?
<?php
$array = array("a" => array(1, 2, 3),
"b" => array(4, 5, 6));
$end = end($array);
print_r($end); // gives me 4, 5, 6. I want the value b
Use end with array_keys instead:
$array = array("a" => array(1, 2, 3),
"b" => array(4, 5, 6));
$keys = array_keys($array);
$end = end($keys);
print_r($end);
Note that since end adjusts the array pointer (hence you can't pass the output from array_keys directly to end without a notice level error), it's probably preferable to simply use
echo $keys[count($keys)-1];
Simply
$array = array("a" => array(1, 2, 3),"b" => array(4, 5, 6));
end($array);
echo key($array);
Output
b
Sandbox
the call to end puts the internal array pointer at the end of the array, then key gets the key of the current position (which is now the last item in the array).
To reset the array pointer just use:
reset($array); //moves pointer to the start
You cant do it in one line, because end returns the array element at the end and key needs the array as it's argument. It's a bit "Weird" because end moves the internal array pointer, which you don't really see.
Update
One way I just thought of that is one line, is to use array reverse and key:
echo key(array_reverse($array));
Basically when you do array_reverse it flips the order around and returns the reversed array. We can then use this array as the argument for key(), which gets the (current) first key of our now backwards array, or the last key of the original array(sort of a double negative).
Output
b
Sandbox
Enjoy!
A simple way to do it would be to loop through the keys of the array and store the key at each index.
<?php
$array = array("a" => array(1, 2, 3),
"b" => array(4, 5, 6));
foreach ($array as $key => $value) $end = $key;
// This will overwrite the value until you get to the last index then print it out
print_r($end);
Can an array key in PHP be a string with embedded zero-bytes?
I wanted to implode a multi-part key with embedded zero-bytes as the delimiter and use it as the key in an associative array, but it doesn't seem to be working. Not sure whether this is a problem with the array access or with array_keys_exists().
Does anybody have any idea? Am I going about this the wrong way? Should I be creating a multi-part key in another way?
To clarify, I am trying to eliminated duplicates from user-entered data. The data consists of a product ID, a variation ID, and N fields of textual data. Each of the N fields has a label and a value. To be considered a duplicate, everything must match exactly (product ID, variation ID, all the labels and all the values).
I thought that if a create a string key by concatenating the information with null bytes, I could keep an associative array to check for the presence of duplicates.
From the PHP string documentation:
There are no limitations on the values the string can be composed of;
in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere
in the string (however, a few functions, said in this manual not to be
“binary safe”, may hand off the strings to libraries that ignore data
after a NUL byte.)
From the PHP arrays documentation:
A key may be either an integer or a string.
No mention is made of any special case for strings that are array keys.
So, yes.
Like I already said in the comments
print_r(array("\00foo\00bar" => 'works'));
works. However, there is no reason for any of the gymnastics you are doing with implode or serialize or null byte keys.
If you want to see whether arrays are identical, then you can just compare them:
$input1 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
$input2 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
var_dump($input1 === $input2);
will output true whereas
$input3 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'foobarbaz');
var_dump($input1 === $input3);
will give false.
Quoting the PHP Manual on Array Operators:
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Also, PHP has a function for deleting duplicate values from arrays:
array_unique — Removes duplicate values from an array
And when you set the second argument to SORT_REGULAR, PHP will compare the arrays for equality, e.g.
$data = array(
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 2, 'variation_id' => 2, 'foo' => 'bar')
);
print_r(array_unique($data, SORT_REGULAR));
will reduce the array to only the first and the third element.
When calling an undefined element of an array, it is showing me a value of another defined element.
Example of array structure:
$array = array(
'a' => array(
'b' => 'c'
)
);
When using echo command on $array['a']['b']['x'] it is showing me value of 'c'. Why this happens I really don't understand since $array['a']['b']['x'] is not defined.
And then when I try to add another value by using command $array['a']['b']['x'] = 'y';
It is rewriting the value of $array['a']['b'] to 'y'
Somehow I really don't understand this behaviour, can someone explain how is that possible? And how then I will be able to create a new string value at $array['a']['b']['x'] = 'xyz' to not override $array['a']['b']?
It is actually not related to arrays at all. This is a string problem.
In PHP you can access and modify characters of a string with array notation. Consider this string:
$a = 'foo';
$a[0] gives you the first character (f), $a[1] the second and so forth.
Assigning a string this way will replace the existing character with the first character of the new string, thus:
$a[0] = 'b';
results in $a being 'boo'.
Now what you do is passing a character 'x' as index. PHP resolves to the index 0 (passing a number in a string, like '1', would work as expected though (i.e. accessing the second character)).
In your case the string only consists of one character (c). So calling $array['a']['b']['x'] = 'y'; is the same as $array['a']['b'][0] = 'y'; which just changes the character from c to y.
If you had a longer string, like 'foo', $array['a']['b']['x'] = 'y'; would result in the value of $array['a']['b'] being 'yoo'.
You cannot assign a new value to $array['a']['b'] without overwriting it. A variable can only store one value. What you can do is to assign an array to $array['a']['b'] and capture the previous value. E.g. you could do:
$array['a']['b'] = array($array['a']['b'], 'x' => 'xyz');
which will result in:
$array = array(
'a' => array(
'b' => array(
0 => 'c',
'x' => 'xyz'
)
)
);
Further reading:
Arrays
Strings
I have an array where I want to use array_slice to remove the first element of the array. Here's the command:
$myArray = array_slice($myArray, 1);
Now, array_slice has a 4th argument, when set to true, it preserves the array keys instead of resetting them. I do need this option set to true.
The 3rd argument is to specify the length of the resulting array. You are supposed to leave this argument out if you want the array to be sliced to the end of the array instead of specifying a length.
So I tried this:
$myArray = array_slice($myArray, 1, NULL, true);
And this results in an empty array. What am I doing wrong? Is there another way to "leave out" the length argument without setting it to NULL? Because setting it to NULL seems to empty my array completely.
Also, my workaround is to do this:
$myArray = array_slice($myArray, 1, count($myArray)-1, true);
but it doesn't seem like I should have to do that...
UPDATE
This appears to be a bug with PHP 5.1.6
I just tested this code:
$myArray = array(
'test1' => 'test1',
'test2' => 'test2',
'test3' => 'test3',
'test4' => 'test4',
);
var_dump(array_slice($myArray, 1, null, true));
And it works fine for me by only showing test2, test3, and test4.
This was run on 5.2.13. Try upgrading PHP (I know I should too but this is a dev box).
try this
$myArray = array_slice($myArray, 1, -1, true);
Couldn't you also use array_shift to remove an array's 1st element?
EDIT: It seems you want to preserve numerical keys, never mind then.