search
HomeBackend DevelopmentPHP TutorialHow to print a solid and hollow diamond shape with side length N_PHP tutorial

How to print a solid and hollow diamond with side length N in php

This article mainly introduces how to print a solid and hollow diamond with side length N in php Methods and examples analyze the techniques of drawing graphics using PHP loop statements. Friends in need can refer to it

The example in this article describes how PHP prints a solid and hollow diamond shape with side length N. Share it with everyone for your reference. The specific analysis is as follows:

Solid diamond calculation method:
$n: side length
$i: current line, starting from 0
$rows: Total number of rows

Upper part
Number of preceding spaces =$n-$i-1
Number of characters=$i*2+1

Lower part
Number of preceding spaces =$i-$n+1
Number of characters=($rows-$i)*2-1

Use str_pad to reduce for/while loops

The code is as follows:

/**
* Print solid diamond
* @param int $n side length, default 5
* @param String $s characters displayed, default*
* @return String
*/
function solidDiamond($n=5, $s='*'){
$str = '';
// Calculate the total number of rows
$rows = $n*2-1;
// Loop to calculate * for each row
for($i=0; $i if($i $str .= str_pad('', ($n-$i-1), ' '). str_pad('', $i*2+1, $s)."rn";
}else{ // Lower part
$str .= str_pad('', ($i-$n+1), ' '). str_pad('', ($rows-$i)*2-1, $s). "rn";
}
}
return $str;
}
echo ''; <br> echo solidDiamond(5); <br> echo '';

The code is as follows:

*
***
*****
*******
*********
*******
*****
***
*

Hollow diamond calculation method:
$n: side length
$i: current line, starting from 0
$rows: Total number of rows

Upper part
Number of preceding spaces =$n-$i-1
Number of empty spaces =$i*2+1-2
Number of characters = $i*2+1 - number of empty spaces

Lower part
Number of preceding spaces =$i-$n+1
Number of empty spaces = ($rows-$i)*2-1-2
Number of characters = ($rows-$i)*2-1 - Number of empty spaces

The code is as follows:

/**
* Print hollow diamond
* @param int $n side length, default 5
* @param String $s characters displayed, default*
* @return String
*/
function hollowDiamond($n=5, $s='*'){
$str = '';
// Calculate the total number of rows
$rows = $n*2-1;
// Loop to calculate * for each row
for($i=0; $i if($i $tmp = $i*2+1;
$str .= str_pad('', ($n-$i-1), ' '). str_pad(str_pad('', $tmp-2, ' ', STR_PAD_BOTH), $tmp, $s, STR_PAD_BOTH). "rn";
}else{ // Lower part
$tmp = ($rows-$i)*2-1;
$str .= str_pad('', ($i-$n+1), ' '). str_pad(str_pad('', $tmp-2, ' ', STR_PAD_BOTH), $tmp, $s, STR_PAD_BOTH). "rn";
}
}
return $str;
}
echo ''; <br> echo hollowDiamond(5); <br> echo '';

The code is as follows:

*
* *
* *
* *
* *
* *
* *
* *
*

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/962925.htmlTechArticleHow to print a solid and hollow diamond with side length N in php. This article mainly introduces how to print a solid and hollow diamond with side length N in php. The method of solid and hollow diamond shapes with side length N, example analysis of php loop statement drawing...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to modify array elements in PHP?How to modify array elements in PHP?May 15, 2025 pm 08:21 PM

Methods to modify array elements in PHP include direct assignment and batch modification using functions. 1. For indexed arrays, such as $colors=['red','green','blue'], the second element can be modified by $colors[1]='yellow'. 2. For associative arrays, such as $person=['name'=>'John','age'=>30], the value of age can be modified by $person['age']=31. 3. Use array_map or array_walk functions to modify array elements in batches, such as $numbers=array_map(fun

How to implement hook function in PHP?How to implement hook function in PHP?May 15, 2025 pm 08:18 PM

Implementing hook functions in PHP can be implemented through observer mode or event-driven programming. The specific steps are as follows: 1. Create a HookManager class to register and trigger hooks. 2. Use the registerHook method to register the hook and trigger the hook by the triggerHook method when needed. Hook functions can improve the scalability and flexibility of the code, but pay attention to performance overhead and debugging complexity.

PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software