Way to apply HTML code to each element of php array [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm building a gallery application and I've been having Issues finding out If there Is a way I can put HTML around each PHP array value In my case images,
I believe that If I echo It I'll get the values as text. I don't want to echo the values as text any options?
Thanks in advance.

If I understand correctly the following may be of some help, If you want to display the images in HTML you could use something like the following.
$images = array(
"1" => "image1.png",
"2" => "image2.jpeg",
"3" => "image3.gif"
);
foreach ($images as $key => $image) {
echo "<img src=\"{$image}\" alt=\"image {$key}\"/>";
}
and if you want to place the images inside HTML and back into your array you can use the following.
$images = array(
"1" => "image1.png",
"2" => "image2.jpeg",
"3" => "image3.gif"
);
foreach ($images as $key => $val) {
$images[$key] = "<img src=\"{$val}\" alt=\"image {$key}\"/>";
}

Not sure if this is just a "coders block", but it's very simple. grab the array, iterate it, wrap the output of each array element in a div and echo it back to the requesting page.
foreach($array as $item):
echo '<div>', $item ,'</div>';
endforeach;

Option 1
You seem to be looking for array_walk:
bool array_walk(array &$Input, callable $Fn [, mixed $extra = null ])
Applies the user-defined function Fn to
each element of the array Input, optionally
passing it the user-specified object $extra.
This is an example of wrapping every element of the array between two user-specified values.
<?php
$arry = array(
'pear',
'orange',
'banana',
);
array_walk($arry, function(&$item, $key, $data) {
$item = $data['before'].$item.$data['after'];
}, array(
'before' => 'this is a ',
'after' => ' squash.',
));
print_r($arry);
?>
Output:
Array
(
[0] => this is a pear squash.
[1] => this is a orange squash.
[2] => this is a banana squash.
)
Option 2
Another option could be that of using preg_replace_callback to perform a bulk replace on each element. This allows greater flexibility both in specifying what to replace, and how to replace it:
<?php
$arry = array(
'pear squash',
'squishy orange',
'squoshed banana',
);
// FIRST - wrap everything in double round brackets
$arry = preg_replace_callback('/^.*$/', function($matches){
return "(($matches[0]))";
}, $arry);
// SECOND - convert anything like "SQUASH" (but with whatever letter instead
// of the "A" - to "juice":
$arry = preg_replace_callback('/(.*)squ(.)sh(.*)/', function($matches){
// $matches[2] contains the whatever letter.
return $matches[1].'juice'.$matches[3];
}, $arry);
print_r($arry);
returns now
Array
(
[0] => ((pear juice))
[1] => ((juicey orange))
[2] => ((juiceed banana))
)

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

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>

Using str_replace() With Array Values Giving Unexpected Results

Using str_replace() to replace values in a couple paragraphs of text data, it seems to do so but in an odd order. The values to be replaced are in a hard-coded array while the replacements are in an array from a query provided by a custom function called DBConnect().
I used print_r() on both to verify that they are correct and they are: both have the same number of entries and are in the same order but the on-screen results are mismatched. I expected this to be straightforward and didn't think it needed any looping for this simple task as str_replace() itself usually handles that but did I miss something?
$replace = array('[MyLocation]','[CustLocation]','[MilesInc]','[ExtraDoc]');
$replacements = DBConnect($sqlPrices,"select",$siteDB);
$PageText = str_replace($replace,$replacements,$PageText);
and $replacements is:
Array
(
[0] => 25
[MyLocation] => 25
[1] => 45
[CustLocation] => 45
[2] => 10
[MilesInc] => 10
[3] => 10
[ExtraDoc] => 10
)
Once I saw what the $replacements array actually looked like, I was able to fix it by filtering out the numeric keys.
$replace = array('[MyLocation]','[CustLocation]','[MilesInc]','[ExtraDoc]');
$replacements = DBConnect($sqlPrices,"select",$siteDB);
foreach ($replacements as $key=>$value) :
if (!is_numeric($key)) $newArray[$key] = $value;
endforeach;
$PageText = str_replace($replace,$newArray,$PageText);
The former $replacements array, filtered to $newArray, looks like this:
Array
(
[MyLocation] => 25
[CustLocation] => 45
[MilesInc] => 10
[ExtraDoc] => 10
)
-- edited: Removed some non sense statements --
#DonP, what you are trying to do is possible.
In my opinion, the strtr() function could be more beneficial to you. All you need to make a few adjustments in your code like this ...
<?php
$replacements = DBConnect($sqlPrices,"select",$siteDB);
$PageText = strtr($PageText, [
'[MyLocation]' => $replacements['MyLocation'],
'[CustLocation]' => $replacements['CustLocation'],
'[MilesInc]' => $replacements['MilesInc'],
'[ExtraDoc]' => $replacements['ExtraDoc'],
]);
?>
This code is kinda verbose and requires writing repetitive strings. Once you understand the way it works, you can use some loops or array functions to refactor it. For example, you could use the following more compact version ...
<?php
// Reference fields.
$fields = ['MyLocation', 'CustLocation', 'MilesInc', 'ExtraDoc'];
// Creating the replacement pairs.
$replacementPairs = [];
foreach($fields as $field){
$replacementPairs["[{$field}]"] = $replacements[$field];
}
// Perform the replacements.
$PageText = strtr($PageText, $replacementPairs);
?>

PHP - searching a body of text with an array of needles, returning the keys of all matches

Looking to search a body of text and return the keys of any of the array elements that have been found within the text. I currently have the below which works but only returns True on the first element found.
$needles = [1 => 'shed', 5 => 'charge', 8 => 'book', 9 => 'car'];
$text = "Does anyone know how much Bentleys charge to put up a small shed please? Thanks";
if(preg_match('/'.implode('|', array_map('preg_quote', $needles)).'/i', $text)) {
echo "Match Found!";
}
However the output I need is;
[1 => 'shed', 5 => 'charge']
Can anybody help? I am going to be searching a lot of values so this needs to be a fast solution hence using preg_match.
The solution using array_filter and preg_match functions:
$needles = [1 => 'shed', 5 => 'charge', 8 => 'book', 9 => 'car'];
$text = "Does anyone know how much Bentleys charge to put up a small shed please? Thanks";
// filtering `needles` which are matched against the input text
$matched_words = array_filter($needles, function($w) use($text){
return preg_match("/" . $w . "/", $text);
});
print_r($matched_words);
The output:
Array
(
[1] => shed
[5] => charge
)

Removing unwanted key/value pair in php array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
above is my output but i want an array like below format. Please help me.
Correct Output:
$data = array ("id"=>"1","name"=>"mani","lname"=>"ssss");
check this, use is is_numeric to check number or string.
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
foreach ($data as $key => $val)
{
if(!is_numeric($key))
{
$new_array[$key] = $val;
}
}
print_r($new_array);
OUTPUT :
Array
(
[id] => 1
[name] => mani
[lname] => ssss
)
DEMO
The Code-Snippet below contains Self-Explanatory Comments. It might be of help:
<?php
// SEEMS LIKE YOU WANT TO REMOVE ITEMS WITH NUMERIC INDEXES...
$data = array( "0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname"=> "ssss"
);
// SO WE CREATE 2 VARIABLES TO HOLD THE RANGE OF INTEGERS
// TO BE USED TO GENERATE A RANGE OF ARRAY OF NUMBERS
$startNum = 0; //<== START-NUMBER FOR OUR RANGE FUNCTION
$endNum = 10; //<== END-NUMBER FOR OUR RANGE FUNCTION
// GENERATE THE RANGE AND ASSIGN IT TO A VARIABLE
$arrNum = range($startNum, $endNum);
// CREATE A NEW ARRAY TO HOLD THE WANTED ARRAY ITEMS
$newData = array();
// LOOP THROUGH THE ARRAY... CHECK WITH EACH ITERATION
// IF THE KEY IS NUMERIC... (COMPARING IT WITH OUR RANGE-GENERATED ARRAY)
foreach($data as $key=>$value){
if(!array_key_exists($key, $arrNum)){
// IF THE KEY IS NOT SOMEHOW PSEUDO-NUMERIC,
// PUSH IT TO THE ARRAY OF WANTED ITEMS... $newData
$newData[$key] = $value;
}
}
// TRY DUMPING THE NEWLY CREATED ARRAY:
var_dump($newData);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
Or even concisely, you may walk the Array like so:
<?php
$data = array(
"0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname" => "ssss"
);
array_walk($data, function($value, $index) use(&$data) {
if(is_numeric($index)){
unset($data[$index]);
}
});
var_dump($data);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
$new_data = array();
foreach($data as $k => $v)
if(strlen($k)>1) $new_data[$k] = $v;
print_r($new_data);
I'm a little confused as to what exactly you're looking for. You give examples of output, but they look like code. If you want your output to look like code you're going to need to be clearer.
Looking at tutorials and documentation will do you alot of good in the long run. PHP.net is a great resource and the array documentation should help you out alot with this: http://php.net/manual/en/function.array.php

Categories