How to call each item in array by name or index? - php

for($i=0; $i<$size; $i++)
{
$firstRow = array_column($data, $i);
foreach($firstRow as $k=>$v)
{
echo $k;//key
echo"---";
echo $v;//value
echo"<br/>";
$val[] =$v;
}
}
RESULT:
0---1
1---1
2---4
3---2
4---8
0---2
1---No items found
2---1
3---2
4---2
How to call individual items in the result above?
If I want to call say 'No items found'...How do I go about it?
ORHow do I use implode to insert the values above into database.
$sql="INSERT INTO contract_item(group_item,item,kuantiti,harga,amount)VALUES ".implode(',', $val);
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
My ultimate goal is to insert the values carried by variable $v into table..ANy good approach is desirable.

A simple if condition in the foreach loop will do the job as shown below
for($i=0; $i<$size; $i++)
{
$firstRow = array_column($data, $i);
foreach($firstRow as $k=>$v)
{
if ($v == "No items found")
{
echo 'No item has been used';
}
else
{
echo $k;//key
echo"---";
echo $v;//value
echo"<br/>";
}
}
}

Try this
for($i=0; $i<$size; $i++)
{
$firstRow = array_column($data, $i);
foreach($firstRow as $k=>$v)
{
echo $k;//key
echo"---";
echo $v;//value
echo"<br/>";
$val[$i][] =$v;
}
}
And the result will be:
RESULT:
[0][0]---1
[0][1]---1
.....
.....
[1][0]---2
[1][1]---No items found
.....
.....

Related

Display values without array (print_r)

I have a function that displays the actors photos from TMDB to my website is there a way that I can make it print without an array, it prints only with print_r I want to know if I can print it like echo or print.
This is the code:
public function getCasts($movieID)
{
if (empty($movieID)) return;
function cmpcast($a, $b)
{
return ($a["order"]>$b["order"]);
}
$temp = $this->_call("movie/" . $movieID . "/casts");
$casts = $temp['cast'];
$temp = array();
if (count($casts) > 0)
{
usort($casts, "cmpcast");
foreach ($casts as &$actor) {
if (!empty($actor['profile_path'])) {
for ($i=6; $i<count($temp['id']); $i++)
if ($temp['name'][$i] == $actor['name']) $temp['char'][$i] .= " / ".str_replace('(voice)', '(hang)', $actor['character']);
if (!in_array($actor['name'], (array) $temp['name'])) {
$temp['pic'][] = "<div style='margin-top:15px;' align='center'><div style='width:140px;margin-right:8px;display:inline-block;vertical-align:top;'><img style='width:130px;height:130px;border-radius:50%;' src='".$this->getImageURL().$actor['profile_path']."'><br />".$actor['name']."<br />".$actor['character']."</div></div>";
}
}
}
}
return $temp;
}
You could use some kind of loop. Use a for loop if you want to limit the number of item you echo.
For example :
$casts = getCasts(1);
for ($i = 0; $i < 5; $i++) {
if (isset($casts['pic'][$i])) {
echo $casts['pic'][$i];
}
}
Hope it helps.

Setting and retrieving values from an array with Checkboxes in PHP

I'm trying to place a value and retrieve it later on
$fruits = array("Watermelon", "Lime", "Lemon");
$result = count($fruits);
$i = 0;
while ($i < $result) {
echo "<br>" . "<input type='checkbox' name='fruit[]' value='$fruits[$i]'>";
echo "$fruits[$i]";
$i++;
}
The first set I assigned the fruit to the value per the array, the code below is supposed to set the values in the if statement and compare them to the checkbox. If I put in the fruit by name it works e.g. "Watermelon" works but "$fruits[0]" does not.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["fruit"])){
$i = 0;
while($i < $result) {
if(in_array('$fruits[$i]', $_POST['fruit'])){
echo "It works!";
$i++;
} else {
$i++;
}
}
} else {
echo "choose a box";
$i = $result;
}
You can do this easily with foreach()(if you want to).
if(isset($_POST['fruit'])) {
foreach($_POST['fruit'] as $fruit) {
$fruits[] = $fruit;
}
if(!empty($fruits)) {
echo 'It Works.!';
} else {
echo "choose a box";
}
}
You use $i++ in work condition so if will increase $i to 1 until last index of $fruits ,if $fruits last index is not exist in $_POST it will nothing display.. use exit can be display.
if(isset($_POST["fruit"])){
$i = 0;
while($i < $result) {
if(in_array($fruits[$i],$_POST['fruit'])){
echo "It works!";
exit;
} else {
$i++;
}
}
}
Also no need to quote in your array...
if(in_array('$fruits[$i]', $_POST['fruit'])) //remove ''

Weird behaviour when searching for char in array string elements

<?php
ini_set('error_reporting', '-1');
ini_set('display_errors', '1');
ini_set('apc.enabled', '0');
gc_enable();
$array = array("php", "php_php", "php_php", "php_php", "php");
$arraysize = count($array);
$style = " style='border: 1px solid black;'";
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
foreach ($array as $key)
{
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
if (strstr($key, "_") !== false)
{
$strstr[] = "found";
$explodedstring1[] = explode("_", $key);
}
else
{
$strstr[] = "not found";
$explodedstring1[] = "not found";
}
if (strpos($key, "_") !== false)
{
$strpos[] = "found";
$explodedstring2[] = explode("_", $key);
}
else
{
$strpos[] = "not found";
$explodedstring2[] = "not found";
}
if (preg_match("/[^_+$]/", $key))
{
$preg_match[] = "found";
$explodedstring3[] = explode("_", $key);
}
else
{
$preg_match[] = "not found";
$explodedstring3[] = "not found";
}
$keysize = strlen($key);
for ($i = 0; $i < $keysize; $i++)
{
if (strcmp($key[$i], "_") === 0) { $strcmpcharcount++; }
}
for ($j = 0; $j < $keysize; $j++)
{
if ($key[$j] === "_") { $equalcmpcharcount++; }
}
if ($strcmpcharcount > 0)
{
$strcmp[] = "found";
$explodedstring4[] = explode("_", $key);
}
else
{
$strcmp[] = "not found";
$explodedstring4[] = "not found";
}
if ($equalcmpcharcount > 0)
{
$equalcmp[] = "found";
$explodedstring5[] = explode("_", $key);
}
else
{
$equalcmp[] = "not found";
$explodedstring5[] = "not found";
}
}
echo "<table$style>
<th$style>
<tr>
<td$style>strstr()</td>
<td$style>strpos()</td>
<td$style>preg_match()</td>
<td$style>strcmp()</td>
<td$style>'==='</td>
</tr>
</th>";
for($k = 0; $k < $arraysize; $k++)
{
echo "<tr>
<td$style>$strstr[$k]</td>
<td$style>$strpos[$k]</td>
<td$style>$preg_match[$k]</td>
<td$style>$strcmp[$k]</td>
<td$style>$equalcmp[$k]</td>
</tr>";
}
echo "</table>";
exit();
?>
The problem is with first two functions - they randomly fails to find the underscore char. In fact I called more than 50 times the script to got proper results. Added and preg_match() test but just to know I'm not sure if it has valid regex.
You're adding new elements to $strstr, $strpos tables and so on and in the end you do for... and printing from these tables where $k keys don't necessarily have to exists.
Check var_dump or print_r on these tables and you will see that in fact they got elements, but their indexes aren't matched with $array indexes (and i guess that's what you want to achieve).
You can change foreach ($array as $key) to foreach ($array as $index => $key) and all occurences like $strstr[] = "found"; to $strstr[$index] = "found"; (also for other recognision methods) and then run the script again to see results.
In last block (for($k = 0; $k < $arraysize; $k++)...) you should either validate if $strstr[$k] (and other arrays) exists before printing it, or print these arrays separately by foreach.
You can also make one table for results and make it multidimensional with function names as keys in the first level and put results in there.

Implode() array and make new line after two elements

I am looking to echo comma separated elements of an array e.g:
Element1, Element2, Element3, Element4, Element5, Element6
However, for the purposes of keeping the echoed elements neat, I might need to go to a new line after the each second element of each line e.g
Element1, Element2,
Element3, Element4,
Element5, Element6
As is I am doing:
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
echo implode(' ,', $labels_array);
?>
And obviously getting:
Element1, Element2, Element3, Element4, Element5, Element6
How then do i do a newline after each second element of a line using implode() or otherwise?
<?php
$labels = array('Element1', 'Element2', 'Element3', 'Element4', 'Element5', 'Element6');
# Put them into pairs
$pairs_array = array_chunk($labels, 2);
# Use array_map with custom function
function joinTwoStrings($one_pair) {
return $one_pair[0] . ', ' . $one_pair[1];
}
$pairs_array = array_map('joinTwoStrings', $pairs_array);
echo implode(',' . PHP_EOL, $pairs_array);
You can use foreach to achive it, im pasting code for you which will give you your desired output
<?php
$labels = array("Element1", "Element2", "Element3", "Element4", "Element5","Element6");
$key = 1;
$lastkey = sizeof($labels);
foreach($labels as $value)
{
if($key%2)
{
if($key==$lastkey)
{
echo $value;
}
else
{
echo $value.",</br>";
}
}
else
{
if($key==$lastkey)
{
echo $value."</br>";
}
else
{
echo $value.",</br>";
}
}
$key++;
}
?>
untested, but something like this should work
$i = 1;
foreach($labels as $label) {
echo $label;
// add a comma if the label is not the last
if($i < count($labels)) {
echo ", ";
}
// $i%2 is 0 when $i is even
if($i%2==0) {
echo "<br>"; // or echo "\n";
}
$i++;
}
For the sake of fancy:
$labels_array=array("Element 1","Element 2","Element 3","Element 4","Element 5","Element 6");
echo implode(",\n",array_map(function($i){ // change to ",<br />" for HTML output
return implode(", ",$i);
},array_chunk($labels_array,2)));
Online demo
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
for($i=0;$i<count($labels_array);$i++)
{ echo($labels_array[$i]);
if($i % 2 != 0)
{
echo("\n");
}else{echo(",");}
}
?>
$i = 1;
$str = '';
foreach($labels AS $label)
{
$str += "$label, ";
if ($i % 2 == 0)
{
$str += "\n";
}
$i++;
}
//Remove last 2 chars
$str = substr($str,0,(strlen($str)-2));
Unless you need the array for something else, this just builds the string...
<?php
$labels = Requisitions::getLabelNames($id);
$s='';
$i=0;
$l=count($labels);
foreach($labels as $label){
$s.=$label['name'];
// Append delimeter. Makes sure every second, and the last one, will be a line break
$s.=((++$i%2)&&($l!=$i))?' ,':"\n";
}
echo $s;
?>
If you do need the array for something, create it first and modify above as needed.

Process array starting with second entry?

I have an array in PHP and would like to use foreach to process entries skipping [0], to process [1], [2], etc.
Thank you
you can use array_slice
$array = array(1,2,3);
foreach (array_slice($array,1) as $value ) {
echo $value;
}
If you don't mind losing first element you can use array_shift
array_shift($array);
foreach ( $array as $value ) {
echo $value;
}
Output
23
$i = 0;
foreach ($ar as $value) {
if ($i > 0) {
// code here
}
$i++;
}
You can keep a variable for this:
$firstSkipped = false;
foreach ($arr as $value) {
if (!$firstSkipped) {
$firstSkipped = true;
continue;
}
// code here
}
Or you could just use a regular for loop, setting the beginning counter to 1:
for ($i = 1, $count = count($arr); $i < $count; $i++) {
// code here
}
You can remove the first entry from an array with array_shift.
$array = array("a","b","c");
array_shift($array);
foreach ($array as $values)
{
echo $values; //bc
}
Try this:
$arr = array(0,1,2,3,4,5);
unset($arr[0]);
foreach($arr as $value) {
echo $value;
echo "<br />";
}
This would delete first entry from array, so it would not skip as you asked, but anyway you can try this...

Categories