What kind of array does PHP use? - php

I can define an array in PHP like this:
$array = array();
In C++, we have two kinds of array.
The first kind is a fixed size array, for example:
int arr[4]; // 4 ints, hardcoded size
The second kind is a dynamic sized array
std::vector<int> v; // can grow and shrink at runtime
What kind of array does PHP use? Are both kinds of arrays in PHP? If so, can you give me examples?

PHP is not as strict as C or C++. In PHP you don't need to specify the type of data to be placed in an array, you don't need to specify the array size either.
If you need to declare an array of integers in C++ you can do it like this:
int array[6];
This array is now bound to only contain integers. In PHP an array can contain just about everything:
$arr = array();
$arr[] = 1;
$arr[] = 2;
$arr[] = 3;
$arr[] = 4;
var_dump($arr); //Prints [1,2,3,4]
$arr[] = 'hello world'; //Adding a string. Completely valid code
$arr[] = 3.14; //Adding a float. This one is valid too
$arr[] = array(
'id' => 128,
'firstName' => 'John'
'lastName' => 'Doe'
); //Adding an associative array, also valid code
var_dump($arr); //prints [1,2,3,4,'hello world',3.14, [ id => 128, firstName => 'John', lastName => 'Doe']]
If you're coming from a C++ background it's best to view the PHP array as a generic vector that can store everything.

From php.net
An array in PHP is actually an ordered map. A map is a type that
associates values to keys. This type is optimized for several
different uses; it can be treated as an array, list (vector), hash
table (an implementation of a map), dictionary, collection, stack,
queue, and probably more. As array values can be other arrays, trees
and multidimensional arrays are also possible.

Basically there are three Usage patterns of array in PHP.
Indexed array: Arrays with sequential numeric index, such as 0, 1, 2, etc. Example:
$myarray = array();
$myarray[0] = "test data 1";
$myarray[1] = "test data 2";
$myarray[3] = "test data 3";
Associative array: This is the most frequently used type of PHP arrays whose elements are defined in key/value pair. Example:
$myarray = array();
$myarray["key1"] = "value 1";
$myarray["key2"] = "value 2";
$myarray["key3"] = "value 3";
Multidimensional array: Arrays whose elements may contains one or more arrays. There is no limit in the level of dimensions. Example:
$myarray = array();
$myarray[0] = array("data01","data02","data03");
$myarray[1] = array("data11","data12","data13");
For more details - Refer to PHP 5 Arrays.

PHP uses three kinds of array:
Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.
Numeric Array Ex:
$numbers = array( 1, 2, 3, 4, 5);
Associative Array Ex:
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
Multidimensional Array Ex:
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

A php array, in C++ terms, is roughly:
std::map< std::experimental::any, std::experimental::any >
where std::experimental::any is a type that can hold basically anything. The php equivalent also can be sorted with the equivalent of <.
Well not quite -- closer to the truth is that a php array is an abstract interface that exposes much of the operations that the above map would provide in C++ (the C++ map is a concrete implementation).
Arrays with contiguous numeric keys stored in the Variant are treated much like a std::vector<Variant>, and under the interface the php system might even use vector<Variant> or something similar to store it, or even have two different internal details, one of which is for contiguous blocks of integer indexed data, and the other for sparse entries. (I don't know how php is implemented, but that is how I would do it)

PHP uses numeric, associative arrays, and multidimensional arrays. Arrays are dynamic in nature, and no size should be mentioned. Go through php.net/manual/en/language.types.array.php to find details.

Related

is there a standard PHP function for transfering an associative array elements to another associative array

Is there a standard PHP function that changes an associative array's index names?
$a1 = array('one'=>1,'two'=>2,'three'=>3);
$new_index_names = array('one'=>'ono','two'=>'dos','three'=>'tres');
$a2 = change_index_names($a1,$new_index_names);
print_r($a2);
// $a2 should have the index names changed accordingly and look like this:
// array('ono'=>1,'dos'=>2,'tres'=>3)
EDIT
Please note that the function needs to know the mappings to the new index names. Meaning, in $new_index_names array provides the mappings. So again, it needs to know that 'ono' is the new index name for 'one'.
EDIT
I know you guys can come up with your own solution, i was wondering there is a standard PHP function that already does this.
EDIT
There are several situations where changing index names would help:
1) separates post value names to generic/internal names so you can separate
your backend code from front-end code.
2) say for instance you have two arrays from post that need to go through the
same exact process, except both arrays although mean/contain same exact type
of values/order/structure, they're index names are different. So when
passing to a function/method that goes by only a set of index names, you'll
need to convert the index names before passing them to that function/method.
You don't need array_values To get your desired output you can just use
array_combine($new_index_names,$a1);
not in just 1 function, but you could use array_values to get the values of the first array, and array_combine to set the new keys
Assuming both arrays has equal count, one way is with array_combine() and array_values()
$a2 = array_combine(array_values($new_index_names), $a1);
The previous answers does not consider the order of $a1 and $new_index_names, so I put my solution following:
$a1 = array('one' => 1, 'two' => 2, 'three' => 3, 'zero' => 0);
$new_index_names = array('zero' => 'zero', 'one' => 'ono', 'two' => 'dos', 'three' => 'tres');
array_combine(
$new_index_names,
str_replace(array_keys($a1), array_values($a1), array_keys($new_index_names))
);
Array
(
[zero] => 0
[ono] => 1
[dos] => 2
[tres] => 3
)
The best answer I've seen thus far:
foreach ($a1 as $k => $v) $a2[$new_index_names[$k]] = $v;
Credits go to jh1711

PHP convert array to serialized string suitable as an array key

I have several associative arrays in PHP that looks like this:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
....
I want to create another associative array, using the serialized values of the previous arrays are used as the array keys. For example:
$newArray = array("data1's serialized key" => "someNewValue", ... );
Are serialized arrays suitable for being used as array keys?
Do they contain any unacceptable characters?
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Are serialized arrays suitable for being used as array keys?
Yup! As far as I know you can use serialized arrays as a key in another array. But the I cannot think of any use-case for this. :P
Do they contain any unacceptable characters?
No, until and unless you specify any unacceptable characters in the original array.
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Nope.
So, you code would look like:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
$serializedArrayKey1 = serialize($data1);
$serializedArrayKey2 = serialize($data2);
$newArray = array($serializedArrayKey1 => "Value for data1", ...);

PHP Prepend two elements to associative array

I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));

PHP - Append elements to array

I have an array that is used to render a graph using PHPGraphLib. I can make this work fine, but only with hard coded values.
I get "POSSIBLE syntax error" warning from Netbeans.
What is the correct way of appending elements to this type of array?
//Create new graph object and add graph data
$graph = new PHPGraphLib(650,400);
$data = array ("00:00" => -9,
"00:15" => -8,
"00:30" => -3.5,
"00:45" => 5,
"01:00" => 11,
"01:15" => 12.5,
"01:30" => 10.5,
"01:45" => 11,
"02:00" => 2,
"02:15" => -2,
"02:30" => 2,
"02:45" => -2,
"03:00" => 14);
array_push($data, "03:15" => 16); //This is the part I cannot get to work
//Plot data
$graph->addData($data);
The syntax to add a new element to an associative array is:
$data["03:15"] = 16;
array_push is used with values, not associative elements. It's normally used only with arrays that have numeric indexes, not associative arrays, as it generates the key by adding 1 to the highest numeric index in the array.
Replace your array_push(...) with this:
$data['03:15'] = 16;
With array_push() you can only add values to arrays. Not keys as you want.
Just append it using shorthand syntax:
$data["03:15"] = 16;

array function to create new array with values as being the keys?

I have an array:
$ids = array(1 => '3010', 2 => '10485', 3 => '5291');
I want to create a new array that takes the values of the $ids array and sets them as the keys of a new array, having the same value.
The final array would be:
$final = array('3010' => 'Green', '10485' => 'Green', '5291' => 'Green');
This will be used in apc_add().
I know I can accomplish this by looping thru it.
$final = array();
foreach($ids as $key => $value):
$final[$value] = 'Green';
endforeach;
But I was wondering if there was php function that does this without having to use a forloop, thanks!
You are looking for array_fill_keys.
$final = array_fill_keys($ids, "Green");
However, be aware that strings that are decimal representations of integers are actually converted to integers when used as array keys. This means that in your example the numbers that end up as keys in $final will have been transformed to integers. Most likely won't make a difference in practice, but you should know about it.
You can do with array_fill_keys this way:
$final = array_fill_keys($ids, "Green");

Categories