What does (array) with two parentheses like this mean in PHP? [duplicate] - php

This question already has answers here:
How to cast variable to array
(8 answers)
Closed 4 years ago.
I've been reading some code recently and I've come across a few instances where the developer would wrap parentheses around like following example.
There's this function:
foreach ((array) $middleware as $m) {
$this->middleware[] = [
'middleware' => $m,
'options' => &$options,
];
}
In the for each check there's array (array) with parentheses around, what do these mean.
Or can someone guide me to a doc where I can read up on this matter.
Thanks in advance.

This is called type casting.
It forces $middleware to an array data type. Some examples:
(array) [1,2] // [1,2]
(array) 1 // [1]
(array) stdClass{hello: world} // [hello => world] (object to array pseudocode)

Related

PHP search an array value inside an array in one line [duplicate]

This question already has an answer here:
Get key from first array on Search Array in Array PHP
(1 answer)
Closed 3 months ago.
I'm using PHP 7.4. I have this array :
$sections = [
'sectionOne' => [
'foo',
'bar',
'hello',
],
'sectionTwo' => [
'yo',
'heya',
],
];
I'd like to build a function to return the section of the received array value
public function getSectionByValue($value) {
return ...
}
If the value is bar then I'll get sectionOne. If the value is yo then I'll get sectionTwo etc...
How can I do to search an array value inside an array ? It is possible to do this in one line ?
You can do something like this inside getSectionByValue function if you really want an one liner.
return key(array_filter($sections, fn($section) => in_array($value, $section)));
If the provided value exists in multiple sections, it will just return the first one.

How to merge two arrays into one and transpose the structure to simplify printing from a loop? [duplicate]

This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 4 months ago.
How can I combine 2 arrays ... :
$array_1 = [['title' => 'Google'], ['title' => 'Bing']];
$array_2 = [['link' => 'www.example1.com'], ['link' => 'www.example2.com']];
In order to get ... :
$array_3 = [
['title' => 'Google', 'link' => 'www.example1.com'],
['title' => 'Bing', 'link' => 'www.example2.com']
];
I guess $array_3 should be structured the following way in order to get :
Final result:
Google - See website
Bing - See website
The function to get the final result:
function site_and_link($array_3) {
foreach ($array_3 as $a) {
echo $a['title'] . " - See website</br>";
}
}
What is the missing step to arrange $array_3?
You can use a simple foreach loop and array_merge to merge both subarrays.
<?php
$result = [];
foreach($array_1 as $index => $val){
$result[] = array_merge($val,$array_2[$index]);
}
print_r($result);
It is indirect programming to use a loop to merge-transpose your array data, then another loop to print to screen.
Ideally, you should try to merge these structures earlier in your code if possible (I don't know where these datasets are coming from, so I cannot advise.)
Otherwise, leave the two arrays unmerged and just write a single loop to print to screen. Because the two arrays are expected to relate to each other by their indexes, there will be no risk of generating Notices.
Since I am typing this out, I'll take the opportunity to reveal a couple of useful tricks:
You can unpack your single-element subarrays by using array syntax with a static key pointing to the targeted variable in the foreach().
Using printf() can help to cut down on line bloat/obfuscation caused by concatenation/interpolation. By writing placeholders (%s) into the string and then passing values for those placeholders in the trailing arguments, readablity is often improved.
Code: (Demo)
$sites = [['title' => 'Google'], ['title' => 'Bing']];
$links = [['link' => 'www.example1.com'], ['link' => 'www.example2.com']];
foreach ($sites as $index => ['title' => $title]) {
printf(
'%s - See website</br>',
$title,
$links[$index]['link']
);
}
Output:
Google - See website</br>
Bing - See website</br>

how to use array_push() [duplicate]

This question already has answers here:
Add values to an associative array in PHP
(2 answers)
Closed 7 years ago.
I want to push new data in array which each value of them.
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3" => "301");
But I got an error syntax.
And if I use like this :
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3", "301");
result is : Array ( [menu1]=>101 [menu2]=>201 [0]=>menu3 [1]=>301 )
My hope the result is : Array ( [menu1]=>101 [menu2]=>201 [menu3]=>301 )
I want push new [menu3]=>'301' but I dont know how. Please help me, the answer will be appreciate
You can use
$array["menu3"] = "301"
as for array_push
array_push() treats array as a stack, and pushes the passed variables onto the end of array
so for associative arrays is a no match
another suitable function for what you want but it requires an array argument is array_merge
$result = array_merge(array("one" => "1"), array("two" => "2"));

Why is this PHP array not the same? [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 4 months ago.
I'm not understanding why the array:
<? $data = array( 'items[0][type]' => 'screenprint'); ?>
Is not the same as
<? echo $data['items'][0]['type']; ?>
I'm trying to add to the array but can't seem to figure out how?
array( 'items[0][type]' => 'screenprint')
This is an array which has one key which is named "items[0][type]" which has one value. That's not the same as an array which has a key items which has a key 0 which has a key type. PHP doesn't care that the key kinda looks like PHP syntax, it's just one string. What you want is:
$data = array('items' => array(0 => array('type' => 'screenprint')));
I hope it's obvious that that's a very different data structure.
It should be:
$data = [
'items' => [['type' => 'screenprint']]
];
echo $data['items'][0]['type'];

Convert a multidimensional array to an XML object in PHP [duplicate]

This question already has answers here:
How to convert array to SimpleXML
(34 answers)
Closed 8 years ago.
I have a multidimensional array like this:
$array = array(
"hello" => "hola",
"another_array" => array(
"key" => "best key ever",
"another" => "yes, another key",
),
"coolarray" => array(
"bool" => true,
"string" => "this is a string!",
),
);
I want a class like this:
class MyClass {
public $array;
public function __construct($array) {
// something
$this->array_to_xml($array);
}
public function array_to_xml($array) {
// convert array to xml
}
Then I want to be able to do things like this:
$string = $this->array->coolarray->string;
How can I do that?
This gets asked a lot
Not sure why you mention XML, sounds like you just want an object.
See this answer for example:
https://stackoverflow.com/a/11854285/543455
$obj = json_decode(json_encode($array));

Categories